本文介绍了属性“Id”是对象的关键信息的一部分,不能修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Entity Framework 4.0,有一个愚蠢的问题,我无法确定。

i'm using Entity Framework 4.0 and having a silly problem that i can't figure out.

我有两个表:


  1. 联系人:Id(主键),值,ContactTypeId(ContactType的外键)

  2. ContactType:Id(主键) ,类型(家庭,单元格,工作等)

实体框架创建了以下两个实体:

Entity Framework created the following two entities:


  1. 联系人:Id,Value,ContactType(导航属性)

  2. ContactType:Id,Type,Contact(Navigation Property) li>
  1. Contact: Id, Value, ContactType (Navigation Property)
  2. ContactType: Id, Type, Contact (Navigation Property)

我正在使用以下代码获取联系人并更新该特定联系人的联系人类型:

I'm using the following code to get the contact and update the contact type for that particular contact:

Contact contact = dbContext.Contacts.Single(c => c.Id == 12345);
contact.ContactType.Id = 3;

抛出以下异常:

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

看起来很简单!我没有得到它

It looks so simple! I don't get it!

推荐答案

框架创建的实体没有contact.ContactTypeId属性。它会自动删除它,并在联系人实体内创建了ContactType关联。

The entity that was created by the framework doesn't have a contact.ContactTypeId property. It automatically removed it and created the ContactType association inside the Contact entity.

正如你所建议的那样,让它工作的方式是通过查询数据库并将其分配给contact.ContactType。例如:

The way to get it to work, as you suggested, is to create a ContactType object by querying the database and assigning it to contact.ContactType. For example:

Contact contact = dbContext.Contacts.Single(c => c.Id == 12345);
ContactType contactType = dbContext.ContactType.Single(c => c.Id == 3);
contact.ContactType = contactType;

这篇关于属性“Id”是对象的关键信息的一部分,不能修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-24 15:04