我第一次使用Entity Framework的Code First样式.我想设置一些默认数据.我遇到的第一种方法涉及创建自定义初始化程序.我已经走了这条路,但是在设置迁移后注意到,Configuration.cs附带了它,它已经覆盖了种子方法,就像自定义初始化程序一样.
I am working with the the Code First style of the Entity Framework for my first time. I want to set up some default data. The first approach I came across involved creating a custom initializer. I was headed this route but noticed after setting up migrations that it came with the Configuration.cs that already overrides the seed method just like the custom initializer.
internal sealed class Configuration : DbMigrationsConfiguration<Toolkit.Model.ToolkitContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(Toolkit.Model.ToolkitContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // } }因此,似乎有两种方法可以完成此任务.有人可以阐明这样做的推荐方法是什么吗?还是根本不重要,我应该扔个硬币吗?
So it seems there are two ways to accomplish this task. Can someone shed some light on what would be the recommended way of doing this? Or does it matter at all and I should just flip a coin?
推荐答案每次模型更改时,都会运行Configuration.cs Seed方法,以确保某些特定数据保留在数据库中,甚至可能重置该数据到指定的默认设置.
The Configuration.cs Seed method will run every time your model changes to make sure that some specific data stays in your DB, or to even possibly to reset that data to a specified default setting.
另一方面,可以将Custom Initializer的seed方法设置为在每次加载应用程序时运行,如下面的代码所示,该代码当前位于我的MVC页面的Global.asax文件中:
The Custom Initializer's seed method, on the other hand, can be setup to run every single time the application loads, like in this code, which is currently in the Global.asax file of my MVC page:
Database.SetInitializer(new MyCustomInitializer<MyDbContext, Configuration>()); var db = new MyDbContext(); db.Database.Initialize(true);在部署应用程序之后,实际的差异才真正发挥作用.自定义初始化程序将确保没有用户可以破坏程序中绝对需要的某些数据.
The practical difference really comes into play after you deploy your application. The Custom Initializer will make sure that no user can destroy some data that's absolutely required in your program.
更多推荐
实体框架代码优先:Configuration.cs种子或自定义初始化程序
发布评论