|
3 | 3 |
|
4 | 4 | namespace SQLite.CodeFirst |
5 | 5 | { |
| 6 | + /// <summary> |
| 7 | + /// An implementation of <see cref="IDatabaseInitializer{TContext}"/> that will recreate and optionally re-seed the |
| 8 | + /// database only if the database does not exist. To seed the database, create a derived class and override the Seed method. |
| 9 | + /// </summary> |
| 10 | + /// <typeparam name="TContext">The type of the context.</typeparam> |
6 | 11 | public class SqliteCreateDatabaseIfNotExists<TContext> : SqliteInitializerBase<TContext> |
7 | 12 | where TContext : DbContext |
8 | 13 | { |
| 14 | + private readonly bool nullByteFileMeansNotExisting; |
| 15 | + |
| 16 | + /// <summary> |
| 17 | + /// Initializes a new instance of the <see cref="SqliteCreateDatabaseIfNotExists{TContext}"/> class. |
| 18 | + /// </summary> |
| 19 | + /// <param name="modelBuilder">The model builder.</param> |
9 | 20 | public SqliteCreateDatabaseIfNotExists(DbModelBuilder modelBuilder) |
10 | | - : base(modelBuilder) { } |
| 21 | + : this(modelBuilder, false) |
| 22 | + { } |
11 | 23 |
|
| 24 | + /// <summary> |
| 25 | + /// Initializes a new instance of the <see cref="SqliteCreateDatabaseIfNotExists{TContext}"/> class. |
| 26 | + /// </summary> |
| 27 | + /// <param name="modelBuilder">The model builder.</param> |
| 28 | + /// <param name="nullByteFileMeansNotExisting">if set to <c>true</c> a null byte database file is treated like the database does not exist.</param> |
| 29 | + public SqliteCreateDatabaseIfNotExists(DbModelBuilder modelBuilder, bool nullByteFileMeansNotExisting) |
| 30 | + : base(modelBuilder) |
| 31 | + { |
| 32 | + this.nullByteFileMeansNotExisting = nullByteFileMeansNotExisting; |
| 33 | + } |
| 34 | + |
| 35 | + /// <summary> |
| 36 | + /// Initialize the database for the given context. |
| 37 | + /// Generates the SQLite-DDL from the model and executs it against the database. |
| 38 | + /// After that the <see cref="Seed" /> method is executed. |
| 39 | + /// All actions are be executed in transactions. |
| 40 | + /// </summary> |
| 41 | + /// <param name="context">The context.</param> |
12 | 42 | public override void InitializeDatabase(TContext context) |
13 | 43 | { |
14 | | - string databseFilePath = GetDatabasePathFromContext(context); |
| 44 | + string databaseFilePath = GetDatabasePathFromContext(context); |
| 45 | + |
| 46 | + var fileInfo = new FileInfo(databaseFilePath); |
| 47 | + |
| 48 | + bool exists; |
| 49 | + if (nullByteFileMeansNotExisting) |
| 50 | + { |
| 51 | + exists = fileInfo.Exists && fileInfo.Length != 0; |
| 52 | + } |
| 53 | + else |
| 54 | + { |
| 55 | + exists = fileInfo.Exists; |
| 56 | + } |
15 | 57 |
|
16 | | - bool dbExists = File.Exists(databseFilePath); |
17 | | - if (dbExists) |
| 58 | + if (exists) |
18 | 59 | { |
19 | 60 | return; |
20 | 61 | } |
|
0 commit comments