Update part of primary key Entity Framework 4.0

后端 未结 2 1818
不思量自难忘°
不思量自难忘° 2021-01-18 05:45

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 SubCa

2条回答
  •  既然无缘
    2021-01-18 06:15

    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).

提交回复
热议问题