title: Attaching objects retrieved from multiple sources
body: <p>I have three classes, Fish (which contains two properties of type Chips and MushyPeas respectively), MushyPeas (which contains a property of type Chips) and Chips (which has a Name property).</p>
  
  <p>I am running the following piece of hypothetical code:</p>
  
  <pre><code>int chipsId;
  using (var db = new FishContext())
  {
      var creationChips = new Chips() { Name = "A portion of chips" };
      db.Chips.Add(creationChips);
      db.SaveChanges();
      chipsId = creationChips.ChipsId;
  }
  
  Chips retrievedChips1;
  using (var db = new FishContext())
  {
      retrievedChips1 = db.Chips.Where(x =&gt; x.ChipsId == chipsId).ToList()[0];
  }
  
  Chips retrievedChips2;
  using (var db = new FishContext())
  {
      retrievedChips2 = db.Chips.Where(x =&gt; x.ChipsId == chipsId).ToList()[0];
  }
  
  using (var db = new FishContext())
  {
      db.Chips.Attach(retrievedChips1);
      db.Chips.Attach(retrievedChips2);
  
      var mushyPeas = new MushyPeas() { Chips = retrievedChips2 };
  
      var fish = new Fish() { Chips = retrievedChips1, MushyPeas = mushyPeas };
      db.Fish.Add(fish);
      db.ChangeTracker.DetectChanges();
      db.SaveChanges();
  }
  </code></pre>
  
  <p>This is to simulate a situation in my real app, in which EF objects (which may actually represent the same database record) are loaded from a variety of different DbContexts and then added to an object tree in another DbContext.</p>
  
  <p>If I don't call the two db.Chips.Attach lines, then brand new Chips entities are created when the Fish object is saved to the database, and assigned new IDs.</p>
  
  <p>Calling db.Chips.Attach solves this issue for one of the retrieved obejcts, but the second Attach call fails with the exception "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."</p>
  
  <p>What is the best way to achieve what I want to achieve here?</p>