共享 PK 和 ObjectContext 错误
我在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来您正在滥用 TPT 继承。为了明确起见,EF 继承的工作方式与 .NET 中的完全相同 - 实体可以是
Offer
类型或OfferEdit
类型。您可以将OfferEdit
转换为Offer
,但它仍然是OfferEdit
。它永远不能是两种类型,这意味着您永远不能拥有Id
与OfferEdit
实体相同的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
orOfferEdit
. You can convertOfferEdit
toOffer
but it is stillOfferEdit
. It can never be of both types which means you can never haveOffer
entity withId
same asOfferEdit
entity because same key cannot be used by two entity instances. You also never can change instance ofOffer
toOfferEdit
because .NET doesn't allow you changing type of existing instance.