Can't Get EF 6 Code First To Create the Tables

ef-code-first entity-framework entity-framework-6


I already have a database with tables outside EF scope. But I want that the tables which will be used by EF to be created automatically.

public class SessionInfo
    public Guid Id {get;set;}
    public string Name { get; set; }
    public DateTime StartsOn { get; set; }
    public DateTime EndsOn { get; set; }
    public string Notes { get; set; }

public class StudentsDbContext:DbContext
    public StudentsDbContext():base("name=memory")

        Database.Log = s => this.LogDebug(s);         


    public DbSet<SessionInfo> Sessions { get; set; }

This code just throws an exception because the table SessionInfoes doesn't exist.

 using (var db = new StudentsDbContext())
       db.Sessions.Add(new SessionInfo() {Id = Guid.NewGuid(), Name = "bla"});           
       var st = db.Sessions.FirstOrDefault();

What do I need to do so that EF will create the "SessionInfoes" (whatever name, it's not important) table by itself? I was under the impression that Ef will create the tables when the context is first used for a change or a query.


After some digging, it seems that EF and Sqlite don't play very nice together i.e at most you can use EF to do queries but that's it. No table creation, no adding entities.

8/5/2014 12:21:55 AM

Accepted Answer

EF needs additional information in order to do this. You'll have to specify an IDatabaseInitializer first. Take a look at this list and find one that is appropriate for your needs (for example: MigrateDatabaseToLatestVersion, DropCreateDatabaseAlways, DropCreateDatabaseIfModelChanges, etc).

Then create your class:

public class MyDatabaseInitializer : MigrateDatabaseToLatestVersion

Then also create the configuration for the initializer (ugh right?):

public  class DatabaseMigrationsConfiguration 
  : DbMigrationsConfiguration<MyDbContext>
    public DatabaseMigrationsConfiguration()
        this.AutomaticMigrationDataLossAllowed = true;
        this.AutomaticMigrationsEnabled = true;

    protected override void Seed(MyDbContext context)
        // Need data automagically added/update to the DB
        // during initialization?


Then one way to initialize the database is:

var myContext = new MyDbContext(/*connectionString*/);

Database.SetInitializer<MyDbContext>(new MyDatabaseInitializer());

Some people prefer the to use the command line to migrate databases, but I don't want to assume I'll always have access to the database from a command lin.

5/23/2017 12:23:47 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow