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

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

Question

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.

Update

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.

1
0
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
  <MyDbContext,
   MyDatabaseMigrationConfiguration>

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?

        base.Seed(context);
    }
}

Then one way to initialize the database is:

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

Database.SetInitializer<MyDbContext>(new MyDatabaseInitializer());
myContext.Database.Initialize(true);

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.

1
5/23/2017 12:23:47 PM


Related Questions





Related

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