我正在使用EntityFramework 5和Code First Migrations。我希望能够做的是根据构建配置指定不同的种子数据。例如:
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将用于确定它是否是新条目的字段。不是我的问题的一部分,但我认为我应该提供正确的方法供将来参考。
答案 0 :(得分:1)
我认为您已经拥有正确的代码(#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
}