Search code examples
c#sql-server.net-coreentity-framework-core

Updating a record that has a Guid primary key and another column that is Identity specification


I have an app that uses a database that is scaffolded to EF using the following command:

dotnet ef dbcontext scaffold "Server=MyServer;Database=MyDatabase;Trusted_Connection=True;Trust Server Certificate=true" 
       Microsoft.EntityFrameworkCore.SqlServer -o Entities -f --no-onconfiguring

When it generates the entities, the table in question has the following set:

entity.Property(e => e.RecNo).ValueGeneratedOnAdd();

The problem comes when I try to update records for this table.

I get an error:

Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.

Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot update identity column 'RecNo'.

It would seem that the ValueGeneratedOnAdd setting would apply during updates as well adds, but this doesn't seem to be the case. Is there something else, preferably during scaffolding, that I could add to make it work?


Solution

  • Try adding this:

    ValueGeneratedOnAdd().Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);