Search code examples
entity-frameworkentity-framework-4.1ef-code-firstsql-server-ce-4

How to implement IDatabaseInitializer with SQL Server CE 4.0


I'm new to EF Code First.

I created a subclass of DbContext and added some DbSets.

I made subclass of DropCreateDatabaseAlways<MyContext> and implemented the following in the context, here is what my context looks like:

public class Context : DbContext
{
  public Context() : base("Database") {  }

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    Database.DefaultConnectionFactory.CreateConnection("System.Data.SqlServerCe.4.0");
    Database.SetInitializer(new DatabaseInitializer());
  }

  public DbSet<NameEntity> Names { get; set; }
  public DbSet<Case> Cases { get; set; }
}

After I run the following and check the apps files I don't see a generated database:

public App() //App ctor
{
  using (Models.Context context = new Models.Context())
  {

  }
}

What am I missing?


Solution

  • You must force EF somehow to create database. It can be done by:

    • Using context (either storing something or reading something) - Seed operation doesn't count in this case because Seed is executed after database is initialized but you need something to trigger initialization
    • Manually force initialization

    Example:

    context.Database.Initialize(false);