title: How can I have Entity Framework work with my detached object graph?
body: <p>In my application we are getting a new instance of our <code>DbContext</code> for each HTTP request. In the normal workflow, we create an entity and start populating portions of it's navigation properties:</p>
  
  <pre><code>// Request 1
  var foo = new Foo();
  SessionStore.Add("Foo", foo);
  
  // Request 2
  var bar = BarDataService.GetBar(barId);
  
  var foo = SessionStore.Get&lt;Foo&gt;("Foo");
  foo.Bars.Add(bar);
  
  // Request 3
  var baz = BazDataService.GetBaz(bazId);
  
  var foo = SessionStore.Get&lt;Foo&gt;("Foo");
  foo.Baz = baz;
  </code></pre>
  
  <p>Once the object graph is fully populated, we insert the entity into the database:</p>
  
  <pre><code>var foo = SessionStore.Get&lt;Foo&gt;("Foo");
  FooDataService.Add(foo); // BOOM!
  </code></pre>
  
  <p>The Add ordinarily just adds the entity to the <code>DbSet</code> and then calls save changes:</p>
  
  <pre><code>Set.Add(entity);
  Context.SaveChanges();
  </code></pre>
  
  <p>Clearly, this fails due to the fact that the <code>foo</code> object contains multiple proxy objects, each of which are attached to different <code>DbContexts</code>. The solution we decided upon was to detach objects that we were receiving:</p>
  
  <pre><code>// Request 2 (modified)
  var bar = BarDataService.GetBar(barId);
  BarDataService.Detach(bar);
  foo.Bars.Add(bar);
  
  // Similar code for Request 3
  
  var foo = SessionStore.Get&lt;Foo&gt;("Foo");
  FooDataService.Add(foo); // Works
  </code></pre>
  
  <p>This works, <em>except</em> for the fact that this now creates new instances of the <code>Bar</code> and <code>Baz</code> objects. </p>
  
  <p>What am I doing wrong here?</p>