2012-10-23 43 views
3

我使用EntityFramework 5與代碼優先遷移。我想要做的是根據構建配置指定不同的種子數據。例如:EntityFramework遷移 - 每構建配置播種

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有沒有內置的方法,我錯過了做這種事情?

感謝

UPDATE

我到底使用的代碼是:

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 
} 

這是爲雅尼克說,但在AddOrUpdate方法,你需要在傳遞EF將用它來確定它是否爲新條目。不是我的問題的一部分,但認爲我應該提供正確的方法供將來參考。

回答

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 
} 
相關問題