EF CORE:如何修改实体拥有的集合

EF CORE: How to modify owned collection on entity

我有实体 "MyEntity",其中包含所有者列表。每个所有者对象都有 3 个属性 - Id、type、link。 在配置中,我将其映射为拥有的对象。

builder.OwnsMany(a => a.Owner, ownershipBuilder =>
        {
            ownershipBuilder.HasKey(x => x.Link);
            ownershipBuilder.Property(x => x.Id).IsRequired();
            ownershipBuilder.Property(x => x.Type)
                .HasConversion(t => t.ToString(),
                value => (MyType) Enum.Parse(typeof(MyType), value))
                .IsRequired();
        });

现在,当我尝试更新这个所有者集合时,我得到了 DbUpdateConcurrencyException

更新流程为:

  1. 按 ID 查找父实体
  2. 将所有者添加到列表中
  3. 对 dbContext 和 SaveChanges 调用更新方法。

在调用 savechanges 后我得到了异常。

有什么想法吗?

谢谢。

我解决了,

我正在代码中生成 Link(所有者实体),这也是 table 中的关键。因此我必须在实体配置中使用 ValueGeneratedNever。

ownershipBuilder.Property(x => x.Link).ValueGeneratedNever().IsRequired();

问题已解决。