更新主键Entity Framework 4.0的一部分

ozs*_*gal 7 entity-framework-4

我有一个包含compose主键的表(3列):

UTP_ID (ITEMId)
UTS_ID (CategoryID)
USS_ID (SubCategoryID)
Run Code Online (Sandbox Code Playgroud)

当我尝试更改SubCategory时,例如,使用EF 4,我得到以下错误:

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

the property is part of the object's key information and cannot be modified
Run Code Online (Sandbox Code Playgroud)

任何想法?为什么我不能改变它?

Sla*_*uma 7

EF在主键属性值和对象引用之间实现身份映射.它不允许更改同一对象实例的密钥.

我会用直接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);
Run Code Online (Sandbox Code Playgroud)

确保您的实体utl与上下文分离,因为此代码直接写入数据库表,并且实体不会获得有关此更改的任何信息.但这避免了必须删除和重新创建实体(由于数据库中旧行的现有外键约束,这可能是不可能的).