3

我将 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 将用来确定它是否是新条目的字段。不是我的问题的一部分,但认为我应该提供正确的方法以供将来参考。

4

1 回答 1

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
}
于 2012-10-23T10:25:13.933 回答