自升级到 .Net Core 3.1 后无法更新 Entity Framework Core 中的标识列

Cannot update identity column in Entity Framework Core since upgrading to .Net Core 3.1

自从升级到 .Net Core 3.1 后,如果我尝试使用错误 'cannot update identity column in Entity Framework Core' 更新我的实体之一,它就会抛出错误。这发生在附加或分离状态。

这是我的流利配置

modelBuilder.Entity<OrderStatus>(b =>
            {
                b.ToTable("OrderStatus");
                b.HasKey(e => e.OrderStatusId);
                b.HasKey(e => new { e.CompanyId, e.OrderId }); //CompositeKey
                b.Property(e => e.OrderStatusId).UseIdentityColumn();
            });

我获取实体并更新一个值(不是 OrderStatusId)并调用保存,然后就崩溃了。

var orderStatus = _context.OrderStatus.FirstOrDefault();
orderStatus.Total = 500;
_context.Entry(OrderStatus).State = EntityState.Modified;
await _context.SaveChangesAsync();

我看到了这个旧线程 cannot update identity column in Entity Framework Core,其中提到 'fix' 添加

b.Property(e => e.OrderStatusId).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);

这确实有效,但我不知道为什么需要这样做。这是我的应用程序中唯一似乎需要这个的 Table。

仅供参考,我以前 运行 使用的是 EF core 3.0,并尝试升级到 3.1.3,但这没有任何区别。

我现在应该将它添加到我所有的流利定义中吗?

感谢建议!

This indeed does work, but I have no idea why this would be needed. This is the only Table in my application that seems to want this.

Should I be adding this to all of my fluent definitions now?

仅对于 不是 table(或 E​​F Core 中的 Key)的主键 (PK) 的标识列才需要。

这应该很少见 - 这就是为什么你只对那个有问题 table。

但是你真的需要一个复合PK吗(那么身份列的目的是什么)?请注意,对于任何流畅的调用,最后一个 HasKey(定义 PK 的 EF Core 流畅 API)获胜,即这里

b.HasKey(e => e.OrderStatusId);
b.HasKey(e => new { e.CompanyId, e.OrderId }); //CompositeKey

b.HasKey(e => e.OrderStatusId);

没有效果,默认可以更新。但为什么它会在这里?可能是为了有身份 PK 和复合 alternate key?换句话说,如果配置是

b.HasKey(e => e.OrderStatusId);
b.HasAlternateKey(e => new { e.CompanyId, e.OrderId }); //CompositeKey

那么你就不会有这样的问题,也不需要配置 AfterSaveBehavior

而且如果真的要复合PK,那就去掉误导

b.HasKey(e => e.OrderStatusId);

行并使用 SetAfterSaveBehavior 解决方案。