Reputation: 6963
I have table(and also entity in Entity Data Model) Person
with following fields:
Name Type
SocialID String
FirstName String
LastName String
which SocialID
is Primary Key. I want to update value of SocialID
for each record. However when i try to update this field in Entity Framework I get following error:
The property 'SocialID' is part of the object's key information and cannot
be modified.
The code that i get above error is:
foreach (var p in Entity.Persons)
{
p.SocialID= p.SocialID + "00";
Entity.SaveChanges();
}
How I can do this??
Upvotes: 3
Views: 11812
Reputation: 11675
As mentioned by the others, you can't do it in code. You will have to make your update in SQL. Either in a migration or directly in SQL Server Management Studio (or the equivalent if you're using a different database).
UPDATE Person -- Or 'Persons' if that's what your table is called
SET SocialID = SocialID + '00'
It will require a lot more work than this if you have other tables use this column as a foreign key (you'll have to drop the constraints first -- on all tables that reference your primary key -- then fix the data and recreate the constraints). Or as Moe said in the comments, you can set your foreign keys to cascade on update.
Upvotes: 5
Reputation: 191
Why would you want to change the primary key? Entity framework will be using that field to identify the object, you can't change its value while it is the primary key.
Based on the first answer I suggest you change the table Person to have its own primary key, let's say PersonID and mantain the SocialID as a foreign key to the Social table. If you need a person to have several Social records you may need to create other table to correspond the PersonId to several SocialId, removing the SocialId from the person table.
Upvotes: -1
Reputation: 13351
As per my knowledge primary key once generated cant be updated programatically,that defies the purpose of primary key. It'll be better if you insert all your data again with new primary keys and delete old data.
Upvotes: 2