How to update primary key from Entity Framework?

I have a table

eventid int -- not PK key but with autoincrement jobid -- PK autoincrement disabled userid int -- PK autoincrement disabled 

To update the job ID:

 var itemforupdate = context.table.where(n=>n.eventid == someparameter).FirstorDefault() 

I get the item correctly from the database, but on assignment:

 itemforupdate.jobID = 5; context.SaveChanges(); 

after context.SaveChanges() I get an error:

The 'jobID' property is part of the object key information and cannot be changed

How to update jobID from Entity Framework to solve this problem?

+5
source share
1 answer

Updating primary key columns is not good practice in EntityFramework. It confuses EF as it changes the identity of the object and makes saving a copy inside the memory and a copy of the data in data synchronization is very problematic. So this is not allowed.

Just do not update primary keys. Instead, delete one line and insert a new one.

Alternatively, you can directly update the primary key using a stored procedure or other request.

+14
source

All Articles