代码之家  ›  专栏  ›  技术社区  ›  SBFrancies

实体框架核心正在尝试更新模型中标记为标识的列

  •  1
  • SBFrancies  · 技术社区  · 7 年前

    我有一个数据库表,其中一列是 IDENTITY 列(不是手动设置的主键)。我的EF核心模型如下:

    public class Model
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int Id { get; set; }
    
        ...Other fields...
    
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int AnotherId { get; set; }
    }
    

    尽管有注释,但当我对表进行更新时,我发现生成的SQL试图更新 身份 列:

    UPDATE [Model] SET ... [AnotherId] = @p10 ...
    WHERE [Id] = @p29;
    SELECT @@ROWCOUNT;
    

    这显然失败了,导致抛出异常。我正在使用Entity Core 2.0,目前无法升级到2.1。你知道为什么数据注释会被忽略吗?

    2 回复  |  直到 7 年前
        1
  •  1
  •   mjwills Myles McDonnell    7 年前

    您可能想要使用的属性是:

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    

    按照 the docs .

        2
  •  2
  •   Salah Akbari    7 年前

    尝试 Fluent API 在里面 OnModelCreating Context 类。像这样:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
        .Entity<Model>()
        .Property(c => c.AnotherId )
        .UseSqlServerIdentityColumn();
    }
    

    同样,在EF核心2中,应该是这样的:

    modelBuilder.Property(c => c.AnotherId).UseSqlServerIdentityColumn();
    modelBuilder.Property(p => p.AnotherId )
                .Metadata.AfterSaveBehavior = PropertySaveBehavior.Ignore;
    
    推荐文章