title: Using Entity Framework to copy entities between databases
body: <p>Having 2 separate databases with the same schema, I need to copy entities (records) from one database to another using Entity Framework 4.</p>
  
  <p>I'm creating 2 Contexts, but I'm getting the following error when I add one entity to the second Context:</p>
  
  <pre><code>An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
  </code></pre>
  
  <p>I know I can avoid that error if i use the Detach method, but in that case the related entities are lost!</p>
  
  <p>Sample code:</p>
  
  <pre><code>        var cx = new MyEntities();
  
          //eager load related tables
          var allEntities = from x in cx.Reservation.Include("Detail.MoreDetail")
                    select x;
  
          // new instance of context but connected to a second database
          var cx2 = new MyEntities( new ConnectionString...);
          foreach (var e in allEntities)
          {
              //cx.Detach(reservation);  // can't detach, or related entities will be lost
              cx2.AddToReservation(reservation);  // error happens here!
              cx2.SaveChanges();                
          }
  </code></pre>
  
  <p>How can I perform such operation?
  Alternatively, how can I detach the entity without losing the related entities?</p>