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"是对象的关键信息的一部分,不能修改


- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01