【问题标题】:Entity Framework Core: Cannot update identity column 'Id'实体框架核心:无法更新身份列“Id”
【发布时间】:2021-08-14 02:59:36
【问题描述】:

我找到了相关问题,但我的问题似乎有所不同。

运行以下代码:

var dbitem = context.MyDatabaseItems.Single(p => p.Id == someId);
context.Update(dbitem);
context.SaveChanges();

导致“无法更新身份列'Id'”。后面的桌子有点特别。由于不同的原因,“Id”不是主键。主键由其他字段的组合组成。无论我做什么:分离、重新附加等现有项目即使我不更改它,我也无法保存实体(参见代码)。

但是这个 ID 是唯一的并且是自动生成的。

构建器如下:

builder.Property(p => p.Id)
   .ValueGeneratedOnAdd();

builder.HasKey(p => new { p.BusinessDay, p.ClientId, p.Version });

BusinessDay 是 dateTime,CLientId 和 Version 是整数。

这是怎么回事?

【问题讨论】:

    标签: entity-framework-core asp.net-core-3.1


    【解决方案1】:

    有两个元数据属性控制更新行为,称为BeforeSaveBehaviorAfterSaveBehavior

    对于自动生成的keys,假定后者为Ignore,即永不更新。对于非键自动生成的属性,它必须显式配置(请注意,到目前为止还没有流畅的 API,因此您必须直接使用元数据 API),例如

    // First define the new key
    builder.HasKey(p => new { p.BusinessDay, p.ClientId, p.Version });
    
    // Then configure the auto generated column
    // This (especially the `SetAfterUpdateBehavior` call) must be after 
    // unassociating the property as a PK, otherwise you'll get an exception
    builder.Property(p => p.Id)
        .ValueGeneratedOnAdd()
        .Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore); // <--
    

    这不会更改数据库架构(模型),因此不需要迁移。只是 EF Core 更新实体行为。

    【讨论】:

      猜你喜欢
      • 2017-08-09
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 2019-08-21
      • 2018-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多