1

I have data in a SQLite Database. But I can not be sure that it will always be there. So when I start my Program I first want to check if the SQLite Database exists and when not I want to create one with the DbSet's I already have in my DbContext.

public class MaintenanceDB : DbContext
{
    public MaintenanceDB() : base (new SQLiteConnection(new 
SQLiteConnectionStringBuilder { DataSource = "data.sqlite"}.ConnectionString), true)
     { 
     }
     public DbSet<MaintenanceEntry> MaintenanceEntries { get; set; }
     public DbSet<ModuleEntry> ModuleEntries { get; set; }

     protected override void OnModelCreating(DbModelBuilder modelBuilder)
     {
         modelBuilder.Entity<MaintenanceEntry>().ToTable("some Table");
         modelBuilder.Entity<ModuleEntry>().ToTable("some Table");
     }

}

When I delete my SQLite Database and startup my Program again then I want my SQLite Database to be created.

Karl Wolf
  • 268
  • 2
  • 13
  • Could you not just check if the `sqlite` file is present and if not create it new? – Ackdari Aug 08 '19 at 11:20
  • And how do I create a new one? plus when I do this in the constructor it already tries to read the db – Karl Wolf Aug 08 '19 at 11:20
  • Take a look at [this](https://stackoverflow.com/questions/15292880/create-sqlite-database-and-table/15292958) – Ackdari Aug 08 '19 at 11:23
  • Here's a link [https://stackoverflow.com/questions/21159790/how-do-i-check-in-sqlite-whether-a-database-exists-c-sharp] Hope this will help! – Kat Aug 08 '19 at 11:28
  • what do I have to change in my code? So i can still use it from outside – Karl Wolf Aug 08 '19 at 11:30

1 Answers1

0
<connectionStrings>
     <add name="MaintenanceDB" connectionString="" providerName="System.Data.SqLite" />
</connectionStrings>
public class MaintenanceDB : DbContext
{
    public MaintenanceDB() : base ("Name=MaintenanceDB")

And try the solutions below:

var context = new MaintenanceDB();
if (!context.Database.Exists())
    context.Database.Create();

Or

var context = new MaintenanceDB();
context.Database.CreateIfNotExists();

Or create an initializer class as below:

// public class ContentInitializer: DropCreateDatabaseAlways <MaintenanceDB>
// public class ContentInitializer: CreateDatabaseIfNotExists <MaintenanceDB>
public class ContentInitializer: DropCreateDatabaseIfModelChanges <MaintenanceDB>

And put this at the beginning of the application.

Database.SetInitializer (new ContentInitializer ());
William Magno
  • 502
  • 5
  • 6