问题
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
- All calls through repository objects.
- The objects get their objectcontext from a factory class.
- 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