问题描述
如何处理在应用程序启动之前或在数据库生成后需要预先存在的数据的情况。例如,我有一个国家列表,我想在其中加载到数据库后,代码首先生成它。我如何做到这一点?
How do I handle situations in which I need pre-existing data before the app is started or right after the database is generated. For example, I have a list of countries in which I'd like to load into the database after code-first generates it. How do I do this?
应用程序的结构如下:
Repository> ;服务> WebMVC
Repository > Service > WebMVC
xml位于 WebMVC
项目中。
推荐答案
创建自定义初始化程序,它继承自 DropCreateDatabaseIfModelChanges
或 DropCreateDatabaseAlways
接口。 Like:
You create custom initializer, which inherits from DropCreateDatabaseIfModelChanges
or DropCreateDatabaseAlways
interface. Like:
public class EntitiesContextInitializer : DropCreateDatabaseIfModelChanges<-YourDbContext->
然后覆盖Seed方法,如:
And then you overwrite Seed method like:
protected override void Seed(YourDbContext context)
可能如下:
public class EntitiesContextInitializer : DropCreateDatabaseIfModelChanges<EntitiesContext>
{
protected override void Seed(EntitiesContext context)
{
List<Role> roles = new List<Role>
{
new Role {Id=1, Title="Admin"},
new Role {Id=2, Title="ProjectManager"},
new Role {Id=3, Title="Developer"}
};
// add data into context and save to db
foreach (Role r in roles)
{
context.Roles.Add(r);
}
context.SaveChanges();
}
}
编辑:设置完毕后,您必须像Ladislav Mrnka提到的那样设置初始化程序。
After setting this up, you have to set up Initializer too, as Ladislav Mrnka mentioned.
Database.SetInitializer(new EntitiesContextInitializer());
ie:在Global.asax:
ie.: in Global.asax:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
Database.SetInitializer(new EntitiesContextInitializer());
}
不要忘记使用System.Data添加 .Entity;
.....
Don't forget to add using System.Data.Entity;
.....
这篇关于实体框架代码 - 数据库中的第一个默认数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!