实体框架代码优先种子数据库 [英] Entity Framework Code First Seed database
问题描述
我将E.F.与Code First方法结合使用...现在我必须在数据库中填充一些数据...但是我却不容易做到...其他内容尚不清楚... 我已经在Google上搜索过,但是找到的每个解决方案都假设我必须创建一个自定义的初始化...,但是我不想创建一个自定义的初始化..
I am using E.F. with Code First approach... Now I have to fill the database with some data... but I cannot do it easily... Simething is not clear... I have googled but every solution I have found suppose I must create a custom Initilization... but I do not want to create a custom Initialization..
每当我启动一些测试时,我需要的是一种方法删除数据库,重新创建它,并用一些数据填充它.
What I need is a method the everytime I launch some tests DROP the database, RE-CREATE it and fill it with some data.
我试图做的是:
public PublicAreaContext()
: base("PublicAreaContext")
{
Database.SetInitializer<PublicAreaContext>(new DropCreateDatabaseAlways<PublicAreaContext>());
}
然后,我尝试在Configuration
类中强制使用Seed
方法.因此:
Then I have tried to impement the Seed
method inside the Configuration
class. So:
internal sealed class Configuration : DbMigrationsConfiguration<PublicAreaContext>
{
protected override void Seed(PublicAreaContext context)
{
...
}
}
但是当我尝试调试时,我从未进入种子方法...我进入了Configuration
类的构造函数,但没有进入种子...为什么?
But when I try to debug I never go in the seed method... I go in constructor of the Configuration
class, but not in the seed... why?
感谢您的帮助
推荐答案
您在混淆种子方法.创建数据库时可以使用一种初始化程序,而移植时可以使用一种初始化程序.参见 http://blog.oneunicorn.com/2013/05/28/database-initializer-and-migrations-seed-methods/
You are confusing seed methods. There is one for initializers that you can use when your database is created and there is one for migrations. See http://blog.oneunicorn.com/2013/05/28/database-initializer-and-migrations-seed-methods/
由于您一直在使用DropCreateDatabaseAlways,因此迁移将不会运行,因此请执行以下操作:
Since you are using DropCreateDatabaseAlways, migrations won't run, so do something like this:
public static class MyDatabase
{
public static void Initialize()
{
Database.SetInitializer(new MyInitializer());
}
}
public class MyInitializer : DropCreateDatabaseAlways<PublicAreaContext>
{
protected override void Seed(PublicAreaContext context)
{
base.Seed(context);
context.Roles.Add(new Role
{
ID = 1,
Name = "User",
});
context.Roles.Add(new Role
{
ID = 2,
Name = "Admin",
});
context.SaveChanges();
}
}
http://www.techbubbles.com/aspnet/seeding-a-database-in-entity-framework/
这篇关于实体框架代码优先种子数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!