Using Entity Framework to Copy Objects Between Databases

Having two separate databases with the same schema, I need to copy objects (records) from one database to another using Entity Framework 4.

I create 2 contexts, but I get the following error when I add one entity to the second Context:

An entity object cannot be referenced by multiple instances of IEntityChangeTracker. 

I know that I can avoid this error if I use the Detach method, but in this case the related objects are lost!

Code example:

  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(); } 

How can I perform such an operation? Alternatively, how can I detach an object without losing related objects?

+8
c # sql-server entity-framework-4
source share
2 answers

Once the error message is helpful, objects can only belong to one context at a time. To do what you need, you need to Detatch each object from the first context before adding it to the second.

As you said, this will destroy related objects. Unfortunately, you will have to deal with this (annoying) aspect of Detach .

+8
source share
+5
source share

All Articles