17

I have Table

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

To update jobID I do following:

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

I get the item from database correctly, but when assigning:

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

after context.SaveChanges() I get the error:

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

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

James Kolpack
  • 9,331
  • 2
  • 44
  • 59
R01
  • 321
  • 2
  • 4
  • 15
  • I'm no expert with entity framework but can't you set the object's key to be eventid (since it's an auto-increment column anyway)? – Zohar Peled Apr 16 '15 at 12:46
  • i just get item from database using eventid that is unique and trying to update jobid from EF but it gives error – R01 Apr 16 '15 at 12:50
  • 1
    Duplicate of: http://stackoverflow.com/questions/1367751/update-primary-key-value-using-entity-framework – Ulric Apr 16 '15 at 12:54

1 Answers1

30

Updating primary key columns is not a good practice with EntityFramework. It confuses EF because it changes the identity of the object, and makes keeping the in-memory copy and the in-database copy of the data in sync very problematic. So it's not allowed.

Just don't update primary keys. Instead delete one row and insert a new one.

Alternatively you can update the primary key directly with a stored procedure or other query.

sarin
  • 5,227
  • 3
  • 34
  • 63