Update primary key value using entity framework

Viewed 64637

I'm trying to update one value of a compound primary key from within the entity framework and I'm getting this error: "The property 'CustomerID' is part of the object's key information and cannot be modified. "

Here is my code:

Dim customer As Customer = (From c In db.Customer Where c.CustomerID = "xxx" AndAlso c.SiteKey = siteKey).FirstOrDefault
customer.CustomerID = "fasdfasdf"
db.SaveChanges()

It seems too simple. Is it true you can't update a primary key within the entity framework? I can't find any documentation on the topic. Thanks!

7 Answers

If there could be only one instance of the database context at any time then modifying the pk would not be such a problem. But each context instance maintains its own cache and can be caching the record that you want to modify.

EF interactions with the database use the pk (from the context cache) to identify the record(s) that they are querying. If a context object could update the key in persistence, the information that other context objects rely upon to identity that record is immediately and permanently wrong.

In short, if you update the primary key you have invalidated the cache in potentially all other instances of the context, and that would break EF fundamentally. This is one of the bigger reasons why it's a bad idea to update a pk.

You need to delete the old entity and insert it again with a modified ID. The easiest method is to JSON stringify the object to create a clone.

var cloned_account = DeserializeObject<account>(SerializeObject(existing_account));
cloned_account.user_id = 1;

db.account.Remove(existing_account);
db.account.Add(cloned_account);

I would like to suggest that instead of updating primary key, its better to insert another row with new primary key and delete the old one. However you need to be aware to change all the child entities to refer to the new primary key pair

Related