Entity Framework Database.SetInitializer simply not working

The database will only be created when you actually use the context.

If you have overridden the Seed method in your initializer as follows:

protected override void Seed(MyContext context){...}

The Seed code will only run when you use an instance of MyContext.

That is why it works when you use

var ctx = new MyContext();
ctx.Database.Initialize(true);

You could always force it to create by using your context in the Application_Start() method in Global.asax.cs like:

        System.Data.Entity.Database.SetInitializer(new MyInitializer());

        MyContext db = new MyContext();
        db.Database.Initialize(true);
        //or even something like db.Users.Count();

Or it will be created later on when you use your context. It might have looked like it had stopped working because you removed some code that would use the context on application startup.

Leave a Comment