The property #39;Id#39; is part of the object#39;s key information and cannot be modified(属性“Id是对象的关键信息的一部分,不能修改)
问题描述
我正在使用 Entity Framework 4.0 并且遇到了一个我无法弄清楚的愚蠢问题.
i'm using Entity Framework 4.0 and having a silly problem that i can't figure out.
我有两张桌子:
- 联系人:Id(主键)、Value、ContactTypeId(ContactType 的外键)
- ContactType:Id(主键)、类型(Home、Cell、Work 等)
实体框架创建了以下两个实体:
Entity Framework created the following two entities:
- 联系人:Id、Value、ContactType(导航属性)
- 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"是对象的关键信息的一部分,不能修改


基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01