【问题标题】:Entity Framework Code First: Configuration.cs seed or custom initializer实体框架代码优先:Configuration.cs 种子或自定义初始化程序
【发布时间】: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


【解决方案1】:

Configuration.cs Seed 方法将在您的模型每次更改时运行,以确保某些特定数据保留在您的数据库中,甚至可能将该数据重置为指定的默认设置。

另一方面,自定义初始化程序的种子方法可以设置为在应用程序每次加载时运行,就像这段代码一样,目前在我的 MVC 页面的 Global.asax 文件中:

Database.SetInitializer(new MyCustomInitializer<MyDbContext, Configuration>());
var db = new MyDbContext();
db.Database.Initialize(true);

实际差异在您部署应用程序后真正发挥作用。 Custom Initializer 将确保没有用户可以破坏您的程序中绝对需要的某些数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 2023-03-23
    • 1970-01-01
    • 2015-01-15
    • 2015-07-24
    相关资源
    最近更新 更多