DropCreateDatabaseAlways种子不叫 [英] DropCreateDatabaseAlways Seed not called
问题描述
我在获得种子法的问题要在我的自定义数据库初始化调用。我使用的是EF 5.0,并具有以下code:
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();
}
}
这两个类从MVC应用程序一个单独的类库存在。在的Global.asax
,我称之为初始化()
方法:
MyDatabase.Initialize();
该数据库被创建就好了,它只是在种子(MyContext上下文)
方法不叫并且没有数据被放入我的数据库。
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.
推荐答案
您的数据库将在后面当您使用上下文中创建或
你总是可以迫使它通过在Global.asax.cs中的的Application_Start()方法使用上下文来创建这样的:
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);
这篇关于DropCreateDatabaseAlways种子不叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!