共享 PK 和 ObjectContext 错误

发布于 2025-01-08 19:23:47 字数 677 浏览 0 评论 0原文

我在 ASP.NET WebForms 应用程序中使用 EF 4.3。我从模型优先方法开始,使用 ObjectContext 类型的上下文对象和 POCO 代码生成器(通过 T4)。

一开始,上下文是在每个服务方法开始时创建的。在研究性能时,我决定切换到每个 Web 请求的上下文。不幸的是,我遇到了 Table-per-Type 继承的问题。我有两个实体:Offer 和 OfferEdit。它们处于一对一的关系,并且共享相同的主键。基本上,一旦编辑报价,就会创建 OfferEdit(OfferEdits 表)。

我在 Web 请求期间多次查询特定 Offer 实体的上下文。我尝试执行的错误:

var offer = Context.Offer.Where(o => o.Id == offerId).FirstOrDefault()

当此优惠已加载到 Context.Offer.EntitySet 时

EntitySet“RuchEntities.Offer”中的所有对象都必须具有唯一的主键。
但是,“Ruch.Data.Model.OfferEdit”类型的实例和“Ruch.Data.Model.Offer”类型的实例都具有相同的主键 值,'EntitySet=Offer;Id=4139'。

将感谢所有的建议。

I am using EF 4.3 in an ASP.NET WebForms application. I've started with model first approach with context object of type ObjectContext and POCO code generator (via T4).

At the beginning the Context was created at the beginning of every service method. While working on performance I decided to switch to context per web request. Unfortunately I have encountered an issue with Table-per-Type inheritance. I have two entities: Offer and OfferEdit. They are in a one to one relationship, and both share the same primary key. Basically an OfferEdit (OfferEdits table) is created once an Offer is being edited.

I query the context for a particular Offer entity more then once during web request. The error I get trying to execute:

var offer = Context.Offer.Where(o => o.Id == offerId).FirstOrDefault()

when this offer is already loaded to Context.Offer.EntitySet is

All objects in the EntitySet 'RuchEntities.Offer' must have unique primary keys.
However, an instance of type 'Ruch.Data.Model.OfferEdit' and an instance of type'Ruch.Data.Model.Offer' both have the same primary key
value,'EntitySet=Offer;Id=4139'.

Will appreciate all advice.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦里寻她 2025-01-15 19:23:47

听起来您正在滥用 TPT 继承。为了明确起见,EF 继承的工作方式与 .NET 中的完全相同 - 实体可以是 Offer 类型或 OfferEdit 类型。您可以将 OfferEdit 转换为 Offer,但它仍然是 OfferEdit。它永远不能是两种类型,这意味着您永远不能拥有 IdOfferEdit 实体相同的 Offer 实体,因为相同的密钥不能被两个使用实体实例。您也永远无法将 Offer 的实例更改为 OfferEdit,因为 .NET 不允许您更改现有实例的类型。

Sounds like you are misusing TPT inheritance. To make it clear EF inheritance works exactly same way as in .NET - the entity can be either of type Offer or OfferEdit. You can convert OfferEdit to Offer but it is still OfferEdit. It can never be of both types which means you can never have Offer entity with Id same as OfferEdit entity because same key cannot be used by two entity instances. You also never can change instance of Offer to OfferEdit because .NET doesn't allow you changing type of existing instance.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文