title: Entity Framework Multiple Object Contexts
body: <p>This question has been asked 500 different times in 50 different ways...but here it is again, since I can't seem to find the answer I'm looking for:</p>
  
  <p>I am using EF4 with POCO proxies.</p>
  
  <p>A. 
  I have a graph of objects I fetched from one instance of an ObjectContext. That ObjectContext is disposed.</p>
  
  <p>B. 
  I have an object I fetched from another instance of an ObjectContext. That ObjectContext has also been disposed. </p>
  
  <p>I want to set a related property on a bunch of things from A using the entity in B....something like</p>
  
  <pre><code>foreach(var itemFromA in collectionFromA)
  {
     itemFromA.RelatedProperty = itemFromB;
  }
  </code></pre>
  
  <p>When I do that, I get the exception:</p>
  
  <pre><code>System.InvalidOperationException occurred
    Message=The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.
    Source=System.Data.Entity
    StackTrace:
         at System.Data.Objects.DataClasses.RelatedEnd.Add(IEntityWrapper wrappedTarget, Boolean applyConstraints, Boolean addRelationshipAsUnchanged, Boolean relationshipAlreadyExists, Boolean allowModifyingOtherEndOfRelationship, Boolean forceForeignKeyChanges)
         at System.Data.Objects.DataClasses.RelatedEnd.Add(IEntityWrapper wrappedEntity, Boolean applyConstraints)
         at System.Data.Objects.DataClasses.EntityReference`1.set_ReferenceValue(IEntityWrapper value)
         at System.Data.Objects.DataClasses.EntityReference`1.set_Value(TEntity value)
         at 
  </code></pre>
  
  <p>I guess I need to detach these entities from the ObjectContexts when they dispose in order for the above to work... The problem is, detaching all entities from my ObjectContext when it disposes seems to destroy the graph. If I do something like:</p>
  
  <pre><code>objectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified | EntityState.Unchanged)  
  .Select(i =&gt; i.Entity).OfType&lt;IEntityWithChangeTracker&gt;().ToList()  
  .ForEach(i =&gt; objectContext.Detach(i));
  </code></pre>
  
  <p>All the relations in the graph seem to get unset.</p>
  
  <p>How can I go about solving this problem?</p>