25

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)

DethoRhyne
  • 930
  • 1
  • 9
  • 29
  • Are you using Fluent API? Any handling for NumericId in OnModelCreating method? – Sanket Aug 27 '16 at 09:37
  • Not directly. I just use `Add-Migration` command to the `ApplicationDBContext` and it generates the code that I use to update the database with.. `Update-Database` command. – DethoRhyne Aug 27 '16 at 16:24
  • Looks like a bug. EF is trying to insert a value into the database-generated column. Could you [submit a new issue](https://github.com/aspnet/EntityFramework/issues/new)? – bricelam Aug 29 '16 at 15:57
  • Technically it shouldn't even be inserting. The value is set and the method called should just be an "Update". I Could try making the property null, maybe then it will ignore it, but I'm afraid if doing that will cause some damage instead. – DethoRhyne Aug 29 '16 at 18:13
  • Missing: the actual code that throws the exception. – Gert Arnold Aug 26 '21 at 20:35

11 Answers11

23

Solution for asp.net core 3.1

modelBuilder.Entity<Type>().Property(u => u.Property).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);
HO3EiN
  • 893
  • 11
  • 17
  • 1
    I can confirm that this does work, but until the scaffolding update with customizations issue is fixed, this solution would get wiped out and have to be retyped anytime you needed to update your models from the database first approach. Perhaps a better approach to use this would be to create a separate class for this instead of placing it directly in your dbContext file – mighty_mite Apr 16 '20 at 18:11
  • @mighty_mite yes. you are right. but i used this for code first approach. – HO3EiN Apr 19 '20 at 08:30
  • This also resolved an issue for me. However I dont understand why a particular entity would need this? Only one of the entities in my code seem to require this line - all other entities update fine without it? – Raj Apr 30 '20 at 01:50
  • 1
    thanks @HO3EiN, Its works for me in Code first approach in Core 3.1 – Pradip Rupareliya May 12 '20 at 06:10
15

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;
jocull
  • 20,008
  • 22
  • 105
  • 149
8

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();
Cooper Wolfe
  • 111
  • 1
  • 7
  • 2
    https://stackoverflow.com/questions/49715467/entity-framework-core-2-0-error-does-not-contain-a-definition-for-usesqlserveri –  Apr 08 '18 at 07:39
8

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.

Malhaar Punjabi
  • 735
  • 7
  • 9
8

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();
        }
Davide Pugliese
  • 366
  • 7
  • 16
2

This line solved my problem. Available from 1.1.1

modelBuilder.Entity<ApplicationUser>().Property(u => u.NumberId).Metadata.IsReadOnlyAfterSave = true;
TonySpark
  • 21
  • 3
2

Solution for asp.net core 5 EF 5

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

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.

Hoodlum
  • 1,443
  • 1
  • 13
  • 24
0

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

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);
benmccallum
  • 1,241
  • 12
  • 27
0

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

Mine.e
  • 1