gpt4 book ai didi

c# - EntityFramework 迁移 - 每个构建配置的播种

转载 作者:行者123 更新时间:2023-11-30 17:57:41 25 4
gpt4 key购买 nike

我将 EntityFramework 5 与 Code First 迁移结合使用。我想要做的是根据构建配置指定不同的种子数据。例如:

protected override void Seed(EFDbContext context)
{
// This will be run in every Build configuration
context.Table1.AddOrUpdate(new Table1 { Field1 = "Foo", Field2 = "Bar" });

#if DEBUG
// This will only be executed if we are Debuging
context.Table1.AddOrUpdate(new Table1 { Field1 = "Blah", Field2 = "De Blah" });
context.Table2.AddOrUpdate(new Table2 { Field1 = "Development Only" });
}

我知道代码可能有误,一旦我知道执行此操作的最佳路线,我就能找出正确的方法调用。

EF 是否有任何我错过做这种事情的内置方法?

谢谢

更新

我最后使用的代码是:

protected override void Seed(EFDbContext context)
{
// This will be run in every Build configuration
context.Table1.AddOrUpdate(t = t.Field1, new Table1 { Field1 = "Foo", Field2 = "Bar" });

#if DEBUG
// This will only be executed if we are Debuging
context.Table1.AddOrUpdate(t = t.Field2, new Table1 { Field1 = "Blah", Field2 = "De Blah" });
context.Table2.AddOrUpdate(t = t.Field1, new Table2 { Field1 = "Development Only" });
#endif
}

正如Yannick 所说,但是在AddOrUpdate 方法中,您需要传入EF 将用于确定它是否为新条目的字段。不是我的问题的一部分,但我认为我应该提供正确的方法以供将来引用。

最佳答案

我认为您已经有了正确的代码(#endif 语句除外)。

这将如您所愿地工作:

protected override void Seed(EFDbContext context)
{
// This will be executed in every Build configuration
context.Table1.AddOrUpdate(new Table1 { Field1 = "Foo", Field2 = "Bar" });

#if DEBUG
// This will only be executed if DEBUG is defined, hence when you are debugging
context.Table1.AddOrUpdate(new Table1 { Field1 = "Blah", Field2 = "De Blah" });
context.Table2.AddOrUpdate(new Table2 { Field1 = "Development Only" });
#endif
}

关于c# - EntityFramework 迁移 - 每个构建配置的播种,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13028142/

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