实体框架代码优先数据库中的默认数据 [英] Entity Framework Code-first default data in database
问题描述
如何处理在应用程序启动之前或数据库生成之后需要预先存在的数据的情况.例如,我有一个国家列表,我想在代码优先生成后将其加载到数据库中.我该怎么做?
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?
应用结构如下:
存储库 >服务>WebMVC
xml 在 WebMVC
项目中.
The xml is in the WebMVC
project.
推荐答案
您创建自定义初始化程序,它继承自 DropCreateDatabaseIfModelChanges
或 DropCreateDatabaseAlways
接口.喜欢:
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)
整个示例可能如下所示:
Whole example might look like:
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();
}
}
设置完成后,您还必须设置 Initializer,正如 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());
}
别忘了添加 using System.Data.Entity;
.....
Don't forget to add using System.Data.Entity;
.....
这篇关于实体框架代码优先数据库中的默认数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!