简体   繁体   中英

.NET 5 - Prevent update on auto-increment column?

I am trying to create an auto-increment field on my Identity Users table called MembershipID, but I am having some issues.

I subclass the Identity user and have created my own "ApplicationUser" so I can add additional fields, and this all works fine.

ApplicationUser.cs

public class ApplicationUser : IdentityUser
{
    public int Currency { get; set; }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int membershipID { get; set; }
    public string Name { get; set; }


}

(NOTE - I have tried both with and without the [key] annotation).

The issue The field is generated and auto-incremented just fine on model creation. However, every single time I update the model, let's say name, I get an error saying:

SqlException: Cannot update identity column 'membershipID'.

Why is that? I thought that by saying it is a database generated value it wouldn't do this? How do I prevent it from updating the column? I am NOT trying to edit the auto-incremented field, I am editing another column but somehow it tries to update the other field as well which causes the issue.

Thanks all.

I found that somebody reported similar issue before. Try to add something like this in your OnModelCreating method if you use core 3.1:

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

Here is similar issue - cannot update identity column in Entity Framework Core . You can find there solutions for earlier versions of core.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM