Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update part of primary key Entity Framework 4.0

I've a table with a compose primary key (3 columns):

UTP_ID (ITEMId)
UTS_ID (CategoryID)
USS_ID (SubCategoryID)

When I try to change SubCategory ,for example,with EF 4 i get follow error:

utl.USS_ID = Convert.ToInt32(ddlSubSetor.SelectedItem.Value);

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

Any Ideias?Why i can't change it?

like image 680
ozsenegal Avatar asked Oct 17 '11 22:10

ozsenegal


1 Answers

EF implements an Identity Map between primary key property values and object references. It doesn't allow to change the key for the same object instance.

I would do this with direct SQL:

objectContext.ExecuteStoreCommand(
    "UPDATE MyTable SET USS_ID = {0} WHERE UTP_ID = {1} AND UTS_ID = {2} AND USS_ID = {3}",
    Convert.ToInt32(ddlSubSetor.SelectedItem.Value),
    utl.UTP_ID, utl.UTS_ID, utl.USS_ID);

Make sure that your entity utl is detached from the context because this code directly writes into the database table and the entity doesn't get any information about this change. But this avoids having to delete and recreate the entity (which might be impossible due to existing foreign key constraints on the old row in the database).

like image 110
Slauma Avatar answered Oct 11 '22 07:10

Slauma