Reputation: 430
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.
Upvotes: 11
Views: 11673
Reputation: 12324
In my situation, Seed was not called because I had enabled migrations. When I removed migrations it worked. http://entityframework.codeplex.com/workitem/1689
Upvotes: 3
Reputation:
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);
Upvotes: 13
Reputation: 1039498
The Seed
method will be called once you send the first SQL query to your database, not in your Application_Start
. For example:
using (var ctx = new MyContext())
{
var rolesCount = ctx.Roles.Count(); // should return 2
}
Upvotes: 1