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"是对象的关键信息的一部分,不能修改
基础教程推荐
- SSE 浮点算术是否可重现? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30