【问题标题】:How do I avoid duplicate rows when seeding?播种时如何避免重复行?
【发布时间】:2012-12-03 15:25:19
【问题描述】:

这是配置文件:

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

【问题讨论】:

    标签: .net entity-framework ef-code-first entity-framework-migrations


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 如果有两列我想比较怎么办?
    • 试试x =&gt; new { x.Prop1, x.Prop2 }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 2021-11-17
    • 2010-12-19
    • 2017-07-29
    • 1970-01-01
    • 2016-05-17
    • 2020-05-22
    相关资源
    最近更新 更多