Entity Framework Error “The property ‘id’ is part of the object’s key information and cannot be modified”
17-Aug-1313 Leave a comment
If you load an entity then change its key you may get this message.
If you really must change the key, for instance on an entity which does not use identity, then you may set the entity’s state to Added then change the key, then change the state to Unchanged.
To change state you could use
Sub SetEntityState(myObject As Object, myState As System.Data.Entity.EntityState) context.Entry(myObject).State = myState End Sub
— Original 8-Jul-2013 —
In my case this was because I was using context.Products.Find(123) and then manipulating the item, perhaps adding it again. So the Find method will cache it the first time. So if you want to do a subsequent Add/Modify then perhaps best to clear that store. You can do this with.
For each p as product in context.products context.enty(p).state = detached next
It was not that the key was wrong.