【发布时间】:2012-12-20 20:56:11
【问题描述】:
我是第一次使用实体框架的代码优先样式。我想设置一些默认数据。我遇到的第一种方法是创建一个custom initializer。我走上了这条路线,但在设置迁移后注意到它与 Configuration.cs 一起已经覆盖了种子方法,就像自定义初始化程序一样。
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" }
// );
//
}
}
看来有两种方法可以完成这项任务。有人可以阐明推荐的这样做方式吗?或者这根本不重要,我应该掷硬币?
【问题讨论】:
-
诚实的问题:如果框架已经为您提供了模板,为什么不遵循约定呢?您的自定义初始化程序是否有很大不同,或者它带来的好处比框架建议的要多?
-
@MilkyWayJoe 我稍后可能需要自定义初始化程序,以便我可以在我的开发盒上初始化到与 localdb 或 sqlexpress 不同的数据库。但是,我仍然想知道是否有理由以一种或另一种方式处理默认数据。
-
不太确定这是否重要。除非您对每个环境都有不同的数据集,否则应该没问题,因为您的 DBContext 应该知道它正在与哪个数据库通信,因为它在您的 connectionString 中定义
标签: c# entity-framework ef-code-first