更新主键Entity Framework 4.0的一部分 [英] Update part of primary key Entity Framework 4.0

查看:190
本文介绍了更新主键Entity Framework 4.0的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

当我尝试更改SubCategory时,例如,与EF 4我得到跟随错误:

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?

推荐答案

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

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.

我将使用直接SQL执行此操作:

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

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

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

这篇关于更新主键Entity Framework 4.0的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆