gpt4 book ai didi

entity-framework - 在 Entity Framework 4.3 中增量播种数据的最佳方法

转载 作者:行者123 更新时间:2023-12-03 07:08:19 24 4
gpt4 key购买 nike

我一直在现有数据库上使用 Entity Framework 4.3,并且我尝试满足一些场景。

首先,如果我删除数据库,我希望 EF 从头开始​​重新创建 - 我已成功使用 CreateDatabaseIfNotExists 数据库初始化程序来实现此目的。

其次,如果我更新模型并且数据库已经存在,我希望数据库自动更新 - 我已成功使用 Entity Framework 4.3 迁移来实现此目的。

这是我的问题。假设我向模型添加了一个需要一些引用数据的新表,那么确保在数据库初始化程序运行时以及迁移运行时创建此数据的最佳方法是什么。我的愿望是,当我从头开始创建数据库时,以及当数据库因迁移运行而更新时,都会创建数据。

在一些 EF 迁移示例中,我看到人们在迁移的 UP 方法中使用 SQL() 函数来创建种子数据,但如果可能的话,我宁愿使用上下文来创建种子数据(正如您在大多数数据库中看到的那样)初始化程序示例),因为对我来说,当 EF 的整个想法将其抽象出来时,您会使用纯 sql,这似乎很奇怪。我尝试在 UP 方法中使用上下文,但由于某种原因,当我尝试将种子数据直接添加到创建表的调用下方时,它认为迁移中创建的表不存在。

非常感谢任何智慧。

最佳答案

如果您想使用实体来播种数据,您应该在迁移配置中使用 Seed 方法。如果您生成新项目Enable-Migrations,您将获得以下配置类:

internal sealed class Configuration : DbMigrationsConfiguration<YourContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}

protected override void Seed(CFMigrationsWithNoMagic.BlogContext 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" }
// );
//
}
}

迁移种子数据的方式不是很有效,因为它应该用于一些非常基本的播种。每次更新新版本都会遍历整个集合并尝试更新现有数据或插入新数据。如果您不使用 AddOrUpdate 扩展方法,则必须手动确保仅在数据尚不存在时才将数据播种到数据库中。

如果您想要有效的播种方式,因为您必须播种大量数据,那么使用 common 会得到更好的结果:

public partial class SomeMigration : DbMigration
{
public override void Up()
{
...
Sql("UPDATE ...");
Sql("INSERT ...");
}

public override void Down()
{
...
}
}

关于entity-framework - 在 Entity Framework 4.3 中增量播种数据的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9342459/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com