DethoRhyne
DethoRhyne

Reputation: 980

cannot update identity column in Entity Framework Core

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)

Upvotes: 28

Views: 32168

Answers (11)

ebadola sobhanverdy
ebadola sobhanverdy

Reputation: 59

Solution for asp.net core 5 EF 5

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

Upvotes: 3

Mine.e
Mine.e

Reputation: 1

In my case (core 3.1), i noticed, i was labeled to identity another column by mistake , problem solved when i sign the true column as key

Upvotes: 0

benmccallum
benmccallum

Reputation: 1378

Based on the thread on GitHub here, the key (pun intended) is to mark the property as an alternate key, so no attempt is made by EF Core in subsequent updates to try set a value for the underlying identity column which is read-only.

Under the hood it's probably doing the same as other answers, but this would be the semantically correct way to fix it.

Fluent-style configuration:

entityTypeBuilder.HasAlternateKey(e => e.NumericId);

Upvotes: 2

Bayan Al-Atrash
Bayan Al-Atrash

Reputation: 1

Actually this caused by the creation of primary key by entity framework it self although we have an Id column in userIdentity I solved it here in the onModelCreation function inside DBContext

       base.OnModelCreating(modelBuilder);

Upvotes: 0

Hoodlum
Hoodlum

Reputation: 1503

Using 3.1, the key is to make sure the identity value of the object you are updating matches the value of the record in the database. So if your object's ID is 0 but the id of the corresponding row in the database is 99, make sure the object's ID value is set to 99 before you try to save it.

Upvotes: 0

HO3EiN
HO3EiN

Reputation: 1053

Solution for asp.net core 3.1

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

Upvotes: 28

Davide Pugliese
Davide Pugliese

Reputation: 386

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();
        }

Upvotes: 10

Malhaar Punjabi
Malhaar Punjabi

Reputation: 783

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.

Upvotes: 8

jocull
jocull

Reputation: 21085

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;

Upvotes: 15

Cooper Wolfe
Cooper Wolfe

Reputation: 111

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();

Upvotes: 8

TonySpark
TonySpark

Reputation: 21

This line solved my problem. Available from 1.1.1

modelBuilder.Entity<ApplicationUser>().Property(u => u.NumberId).Metadata.IsReadOnlyAfterSave = true;

Upvotes: 2

Related Questions