问题
I've added a separate Identification to the AspNetUsers table called NumericId that will serve along with the GUID like ID that ASP has for default.
I've added the property as an additional property of the ApplicationUser class:
public class ApplicationUser : IdentityUser
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual int NumericId { get; set; }
}
However, when I try to register, or update the user's details (that aren't even relevant to the numericId) I keep getting the error
SqlException: Cannot update identity column 'NumericId'.
which prevents any changes and in the end does not update the user (but it does register one, and Numeric Id is properly assigned on that part. But this is irrelevant)
回答1:
Per the discussion on GitHub surrounding this issue, for EF Core 2.0 we needed to use both lines suggested in other posts.
for Entity framework core 2.0 , The "IsReadOnlyAfterSave" property is deprecated. Use following:
builder.Property(p => p.Id)
.UseSqlServerIdentityColumn();
builder.Property(p => p.Id)
.Metadata.AfterSaveBehavior = PropertySaveBehavior.Ignore;
回答2:
This was a bug with EF Core 1.0. See EF trying to Insert into Identity field.
EF Core 1.2 has marked the issue as fixed, but the workaround without updating is to use
modelBuilder.Entity<Type>().Property(u => u.Property).UseSqlServerIdentityColumn();
回答3:
If you are using EF Core 2.1, you can try that.
builder.Property(e => e.ColumnName).Metadata.AfterSaveBehavior = PropertySaveBehavior.Ignore;
It worked for me.
IsReadOnlyAfterSave is deprecated.
回答4:
I found this other solution (I am using .NET Core 2.1):
using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using YetAnotherERP.Data;
using YetAnotherERP.Entities;
using YetAnotherERP.Exceptions;
using YetAnotherERP.Utils;
namespace YetAnotherERP.Services
{
public class EmployeeRepository : IEmployeeRepository
{
private DataContext _context;
public EmployeeRepository(DataContext dataContext)
{
_context = dataContext;
}
....
public async Task UpdateEmployee(Employee employee)
{
_context.Update(employee).Property(x=>x.Id).IsModified = false;
_context.SaveChanges();
}
回答5:
This line solved my problem. Available from 1.1.1
modelBuilder.Entity<ApplicationUser>().Property(u => u.NumberId).Metadata.IsReadOnlyAfterSave = true;
来源:https://stackoverflow.com/questions/39176018/cannot-update-identity-column-in-entity-framework-core