EF4 can’t add an object to the context even though I’m convinced it is not attached

那年仲夏 提交于 2020-01-06 19:51:19

问题


I can’t add an object to the ObjectContext even though I’m convinced it is not attached and it is not associated with a different context

I am using EF 4 with POCO objects.

If I try

_currentContext.ObjectStateManager.GetObjectStateEntry(entityIn)

Then I get the error

The ObjectStateManager does not contain an ObjectStateEntry with a reference to an object of type 'System.Data.Entity.DynamicProxies.OrderItem_7D361CB49D75AA90681B4BA3F924139ECB0FC1426E38E90C7B884A4E9CD777DF'.

Fair enough it’s not there. So if I try to attach it

_currentContext.AttachTo("OrderItems", entityIn)

Then I get

An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

How can I be getting both errors. Don’t they contradict?? How can I attach it to the context?

Edit

There is only one context throughout the app. The pattern is

  1. All calls through repository objects.
  2. The objects get their objectcontext from a factory class.
  3. This factory class either creates a context or gets the context from the request object thus guaranteeing only one context is used for the page lifecycle

At any point if you take two instantiations of the context object the hash code for each one is the same.


回答1:


The object, entityIn probably has a reference to an object which is in another context.

However, the real problem here is that you have multiple contexts in scope at all. It is hard to do that right. In a web application, you should have one context per request, period.



来源:https://stackoverflow.com/questions/8124743/ef4-can-t-add-an-object-to-the-context-even-though-i-m-convinced-it-is-not-attac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!