属性“Id"是对象的关键信息的一部分,不能修改

The property #39;Id#39; is part of the object#39;s key information and cannot be modified(属性“Id是对象的关键信息的一部分,不能修改)

本文介绍了属性“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(主键)、Value、ContactTypeId(ContactType 的外键)
  2. ContactType:Id(主键)、类型(Home、Cell、Work 等)

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

Entity Framework created the following two entities:

  1. 联系人:Id、Value、ContactType(导航属性)
  2. ContactType:Id、Type、Contact(导航属性)

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

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 属性.它会自动删除它并在 Contact 实体中创建 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来创建一个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"是对象的关键信息的一部分,不能修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:属性“Id"是对象的关键信息的一部分,不能修改

基础教程推荐