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}”。

4

1 回答 1

1

由于您没有指定标识符表达式,因此 EF 按主键进行比较(未出现在您的对象初始化程序中)

如果 ID 已知,则指定它,或者使用不同的表达式。例如:

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

在这种情况下,它将匹配现有记录Title

于 2012-12-03T15:56:16.700 回答