I'm having an issue getting the Seed method to be called on my custom Database initializer. I'm using EF 5.0 and have the following code:
public static class MyDatabase
{
public static void Initialize()
{
Database.SetInitializer(new MyInitializer());
}
}
public class MyInitializer : DropCreateDatabaseAlways<MyContext>
{
protected override void Seed(MyContext context)
{
base.Seed(context);
context.Roles.Add(new Role
{
ID = 1,
Name = "User",
});
context.Roles.Add(new Role
{
ID = 2,
Name = "Admin",
});
context.SaveChanges();
}
}
These two classes exist in a separate class library from the MVC app. In the Global.asax
, I call the Initialize()
method:
MyDatabase.Initialize();
The database gets created just fine, it's just the Seed(MyContext context)
method isn't called and no data gets put into my database.
Your database will be created later on when you use your context or 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);