Wednesday, 22 August 2012

Entity Framework - Attach Detach Object Graph

Entity Framework and RIA Services do not allow Entities to be added/removed from cross containers. In order to move Entity from one DomainContext/ObjectContext to another DomainContext/ObjectContext, we need to recursively detach the object graph and attach it to other DomainContext/ObjectContext.Or else we might encounter the following exception -
"cannot be attached to this EntityContainer because it is already attached to another EntityContainer"


So what is going wrong here - School is member of 'ctx' Context and without Detaching it from 'ctx' we are trying at Attach into 'tempctx'. Note every instance of Context has a unique EntityContainer.

Now, solution of this problem is every simple. Before attaching school into 'tempContext' call a Detach on 'ctx' like below - 


Also,  When we try to detach entity from old 'ctx' and attach it to 'tempctx', it may give you an error that "entity with same identity already exists in the EntitySet" and it will throw an exception. In this case we will just simply reuse the existing entity instead of attaching the entity we have.
 
Object Graph
 
Single entity can be easily detached and attached from EntitySet where it belongs, but the problem comes when navigation properties of entity are not empty. Entity object along with navigation properties is called Object Graph because if you notice, navigation property’s navigation property will contain reference to same entity and that will result in endless recursive code for Detach/Attach. Now we will look at the solution to deal Atttach/Detach with the EntityGraph-

Look at the following Detach method, which I have created as a Extension Method  -

And Following is as Attach method -

Now see the difference with the traditional approach i.e 'Method1' it showing the same expected error -

However if take the advantage of the above created Extension method we don't get any such error and the result to as below -

 In my Next Post - I ll address the Partial Submit Changes where l am using the same 'tempctx' to apply SubmitChanges instead of SubmitChanges from the main 'ctx'.

1 comment:

  1. Hi, Nice Blog. Did you have look at EntityGraph. It does the same, but is more flexible and you can do a lot more with it.

    You can find a general description here:
    http://riaservicescontrib.codeplex.com/wikipage?title=EntityGraph

    Partial save and context synchronization is described her:
    http://riaservicescontrib.codeplex.com/wikipage?title=PartialSaveWithEntityGraph

    ReplyDelete