Gurgen Sargsyan
Gurgen Sargsyan

Reputation: 1087

Why does EF core ignore auto increment column and try to update this?

In mssql database I have an auto increment column named AutoIncrementNumber which is configured with this mentioned

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.Entity<User>(entity =>
   {
      entity.Property(e =>e.AutoIncrementNumber).ValueGeneratedOnAdd();
    }
}

I added a new user and want to update this

    var user = new User { UserName = "SomeUserName", Code=0};
    var result = await _userManager.CreateAsync(user, "SomePassword");

    //after CreateAsync user.AutoIncrementNumber == 1

    if (result.Succeeded)
    {
      user.Code = 1;
      userManager.UpdateAsync(user);
    }

but during UpdateAsync I came across with an error

DbUpdateException: An error occurred while updating the entries. See the inner exception for details. SqlException: Cannot update identity column 'AutoIncrementNumber'

Project is running under .net core 1.1

SQL Schema

CREATE TABLE [dbo].[AspNetUsers](
    [Id] [nvarchar](450) NOT NULL,
    [UserName] [nvarchar](256) NULL,
    [AutoIncrementNumber] [int] IDENTITY(1,1) NOT NULL,
    [ReferralCode] [nvarchar](50) NULL,
    CONSTRAINT [PK_AspNetUsers] PRIMARY KEY CLUSTERED (
        [Id] ASC )WITH (
            PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
            IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
            ALLOW_PAGE_LOCKS = ON
        ) ON [PRIMARY]
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Upvotes: 1

Views: 4129

Answers (1)

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131180

ValueGeneratedOnAdd means that the value is generated by the database when inserting an object and the property should be ignored when inserting.

You should use ValueGeneratedOnAddOrUpdate to specify that the value should be excluded from UPDATE as well.

With Data Annotations, the equivalent to ValueGeneratedOnAddOrUpdate is [DatabaseGenerated(DatabaseGeneratedOption.Computed)]. The equivalent to ValueGeneratedOnAdd is [DatabaseGenerated(DatabaseGeneratedOption.Identity)]

Check the Generated Values section in Microsoft Docs.

Upvotes: 5

Related Questions