Asp.net core mvc 无法更新实体框架核心中的标识列

Asp.net core mvc 无法更新实体框架核心中的标识列,asp.net-core-mvc,entity-framework-core,Asp.net Core Mvc,Entity Framework Core,我在AspNetUsers表中添加了一个名为NumericId的单独标识,该标识将与ASP默认使用的类似GUID的ID一起使用 我已将该属性添加为ApplicationUser类的附加属性: public class ApplicationUser : IdentityUser { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public virtual int NumericId { get; set; } }

我在AspNetUsers表中添加了一个名为NumericId的单独标识,该标识将与ASP默认使用的类似GUID的ID一起使用

我已将该属性添加为ApplicationUser类的附加属性:

public class ApplicationUser : IdentityUser
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual int NumericId { get; set; }
}
然而,当我试图注册或更新用户的详细信息(这些信息甚至与numericId无关)时,我总是会遇到错误

SqlException: Cannot update identity column 'NumericId'.

这会阻止任何更改,最终不会更新用户(但它确实注册了一个,并且在该部分上正确分配了数字Id。但这与此无关)

这是EF Core 1.0的一个错误。看

EF Core 1.2已将该问题标记为已修复,但不更新的解决方法是使用

modelBuilder.Entity<Type>().Property(u => u.Property).UseSqlServerIdentityColumn();
modelBuilder.Entity().Property(u=>u.Property).UseSqlServerIdentityColumn();

这一行解决了我的问题。 可从1.1.1获得

modelBuilder.Entity<ApplicationUser>().Property(u => u.NumberId).Metadata.IsReadOnlyAfterSave = true;
modelBuilder.Entity().Property(u=>u.NumberId).Metadata.IsReadOnlyAfterSave=true;
围绕这个问题,对于EF Core 2.0,我们需要使用其他帖子中建议的两行代码

对于Entity framework core 2.0,“IsReadOnlyAfterSave”属性为 不赞成。使用以下内容:


如果您使用的是EF Core 2.1,您可以尝试一下

builder.Property(e => e.ColumnName).Metadata.AfterSaveBehavior = PropertySaveBehavior.Ignore;
这对我有用


IsReadOnlyAfterSave已弃用

我找到了另一个解决方案(我正在使用.NET Core 2.1):


asp.net core 3.1的解决方案

modelBuilder.Entity<Type>().Property(u => u.Property).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);
modelBuilder.Entity().Property(u=>u.Property).Metadata.SetAfterSaveBehavior(propertysavebhavior.Ignore);

使用3.1,关键是确保要更新的对象的标识值与数据库中记录的值匹配。因此,如果对象的ID为0,但数据库中对应行的ID为99,请确保在尝试保存之前将对象的ID值设置为99

实际上这是实体框架自己创建主键造成的 虽然我们在userIdentity中有一个Id列 我在DBContext中的onModelCreation函数中解决了这个问题

       base.OnModelCreating(modelBuilder);

你在使用fluentapi吗?OnModelCreating方法中对NumericId有任何处理吗?不是直接处理。我只需在
ApplicationDBContext
中使用
addmigration
命令,它就会生成我用来更新数据库的代码<代码>更新数据库命令。看起来像个bug。EF正在尝试向数据库生成的列中插入值。你能吗?从技术上讲,它甚至不应该插入。该值已设置,调用的方法应该只是一个“更新”。我可以尝试将属性设置为null,也许它会忽略它,但我担心如果这样做会造成一些损害。我可以确认这确实有效,但在修复带有自定义项的脚手架更新问题之前,此解决方案将被删除,并且必须在需要从数据库优先方法更新模型时随时重新键入。使用它的更好方法可能是为它创建一个单独的类,而不是将它直接放在dbContext中file@mighty_mite对你是对的。但我将其用于代码优先的方法,这也解决了我的一个问题。但是我不明白为什么一个特定的实体需要这个?我的代码中只有一个实体似乎需要这一行-所有其他实体都可以在没有它的情况下更新?谢谢@HO3EiN,它在Core 3.1的代码优先方法中对我有用。同样的结果。我仍在获取,无法更新标识列“id”错误。
modelBuilder.Entity<Type>().Property(u => u.Property).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);
       base.OnModelCreating(modelBuilder);