无法更新Entity Framework Core中的标识列

Det*_*yne 12 entity-framework-core asp.net-core-mvc

我在AspNetUsers表中添加了一个单独的标识,名为NumericId,它将与ASP具有的默认值一样提供GUID.

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

public class ApplicationUser : IdentityUser
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual int NumericId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试注册或更新用户的详细信息(甚至与numericId无关)时,我不断收到错误

SqlException: Cannot update identity column 'NumericId'.
Run Code Online (Sandbox Code Playgroud)

这可以防止任何更改,最终不会更新用户(但它会注册一个,并且在该部分上正确分配了数字ID.但这是无关紧要的)

Hos*_*aei 12

asp.net core 3.1的解决方案

modelBuilder.Entity<Type>().Property(u => u.Property).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);
Run Code Online (Sandbox Code Playgroud)


joc*_*ull 9

根据关于此问题的GitHub讨论,对于EF Core 2.0,我们需要使用其他帖子中建议的两条线.

对于Entity framework core 2.0,不推荐使用"IsReadOnlyAfterSave"属性.使用以下:

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

builder.Property(p => p.Id)
    .Metadata.AfterSaveBehavior = PropertySaveBehavior.Ignore;
Run Code Online (Sandbox Code Playgroud)


Coo*_*lfe 8

这是EF Core 1.0的一个错误。请参阅EF尝试插入身份字段。

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

modelBuilder.Entity<Type>().Property(u => u.Property).UseSqlServerIdentityColumn();
Run Code Online (Sandbox Code Playgroud)

  • /sf/ask/3480082721/ (2认同)

Mal*_*abi 7

如果您使用的是EF Core 2.1,则可以尝试。

builder.Property(e => e.ColumnName).Metadata.AfterSaveBehavior = PropertySaveBehavior.Ignore;
Run Code Online (Sandbox Code Playgroud)

它为我工作。

不推荐使用IsReadOnlyAfterSave。


Dav*_*ese 7

我找到了另一个解决方案(我使用的是 .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();
        }
Run Code Online (Sandbox Code Playgroud)