Why my entity primary key shows to be modified after updating entity?


I have a class ApplicationUser that inherits from IdentityUser. I added the property LastLoggedIn which is OffsetDateTime datatype and I modify it with every request to the API. Also, I am using Audit from entityframework plus to log user add/update/delete operations and this is how I came across this issue. every time I update the ApplicationUser entity's LastLoggedIn property I can see that the Id property has been modified as well, showing same old and new value. Why my primary key is being modified here?

I posting the relevant code,

public class ApplicationUser : IdentityUser {
        [Required, StringLength(50)]
        [Display (Name = "First Name")]
        public string FirstName { get; set; }
        public OffsetDateTime? LastLoggedIn { get; set; }

Method calling the entity, since the class inherits from IdentityUser, I am using UserManager

 public async Task UpdateUserLastActivityDateAsync (string userId, string timeZone) {
            var user = await userManager.FindByIdAsync(userId);
            user.LastLoggedIn = timeZone.GetInstantOffsetDateTime();
            await unitOfWork.CompleteAsync(); //  = context.SaveChangesAsync();

I tried the following but I get an exception,

        .Property(e => e.Id)
        .Metadata.BeforeSaveBehavior = PropertySaveBehavior.Ignore;

The property 'Id' cannot be configured as 'ValueGeneratedOnUpdate' or 'ValueGeneratedOnAddOrUpdate' because the key value cannot be changed after the entity has been added to the store.

Accepted Answer

The key property cannot be ignored by design.

That's due to be able to retrieve which row is behind the change. Without the key, you cannot know which ApplicationUser has been modified.

Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why