2012-12-03 203 views
1

下面是配置文件:播種時如何避免重複行?

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

    protected override void Seed(Context context) 
    { 
     //my seeding DB, here's an example 
     context.HomePageAreas 
      .AddOrUpdate(new HomePageArea { Title = HomePageArea.TopAreaKey }); 
    } 
} 

應用程序啓動:

Database.SetInitializer<Context>(
    new MigrateDatabaseToLatestVersion<Context, Configuration>()); 

using (var context = new Context()) 
    context.Database.Initialize(false); 

然後我得到的每一個添加的行的DbEntityValidationException(從第二個啓動和上):

{0}:已有'{1}'記錄的「{0}」字段設置爲「{2}」。

回答

1

由於您沒有指定的標識符表達,EF是由主鍵進行比較(這並不出現在對象初始化)

要麼指定的Id如果它是已知的,或使用不同的表達式。例如:

context.HomePageAreas 
     .AddOrUpdate(x => x.Title, 
        new HomePageArea { Title = HomePageArea.TopAreaKey }); 

在這種情況下,它將通過Title匹配現有記錄。

+0

如果我想比較兩列,該怎麼辦? – Shimmy

+0

嘗試使用'x => new {x.Prop1,x.Prop2}' –