How to update primary key value in entity framework?

c# entity-framework

Question

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??

1
3
2/1/2013 10:46:53 AM

Accepted Answer

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.

4
2/1/2013 8:34:00 PM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow