Entity Framework Multiple Object Contexts

@Danny Varod is right. You should use one ObjectContext for the whole workflow. Moreover because your workflow seems as one logical feature containing multiple windows it should probably also use single presenter. Then you would follow recommended approach: single context per presenter. You can call SaveChanges multiple times so it should not break your logic.

The source of this issue is well known problem with deficiency of dynamic proxies generated on top of POCO entities combined with Fixup methods generated by POCO T4 template. These proxies still hold reference to the context when you dispose it. Because of that they think that they are still attached to the context and they can’t be attached to another context. The only way how to force them to release the reference to the context is manual detaching. In the same time once you detach an entity from the context it is removed from related attached entities because you can’t have mix of attached and detached entities in the same graph.

The issue actually not occures in the code you call:

itemFromA.RelatedProperty = itemFromB;

but in the reverse operation triggered by Fixup method:

itemFromB.RelatedAs.Add(itemFromA);

I think the ways to solve this are:

  • Don’t do this and use single context for whole unit of work – that is the supposed usage.
  • Remove reverse navigation property so that Fixup method doesn’t trigger that code.
  • Don’t use POCO T4 template with Fixup methods or modify T4 template to not generate them.
  • Turn off lazy loading and proxy creation for these operations. That will remove dynamic proxies from your POCOs and because of that they will be independent on the context.

To turn off proxy creation and lazy loading use:

var context = new MyContext();
context.ContextOptions.ProxyCreationEnabled = false;

You can actually try to write custom method to detach the whole object graph but as you said it was asked 500 times and I haven’t seen working solution yet – except the serialization and deserialization to the new object graph.

Leave a Comment