Có 2 cơ sở dữ liệu riêng biệt với các lược đồ đó, tôi cần phải sao chép các đối tượng (bản ghi) từ một cơ sở dữ liệu khác sử dụng Entity Framework 4.Sử dụng Entity Framework để sao chép các đối tượng cơ sở dữ liệu giữa
tôi là tạo ra 2 bối cảnh, nhưng tôi nhận được lỗi sau khi tôi thêm một thực thể với bối cảnh thứ hai:
An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
tôi biết tôi có thể tránh lỗi nếu tôi sử dụng phương pháp Detach, nhưng trong trường hợp đó các đối tượng liên quan bị mất!
Mẫu mã:
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();
}
Làm thế nào tôi có thể thực hiện thao tác như vậy? Cách khác, làm thế nào tôi có thể tách thực thể mà không làm mất các thực thể liên quan?
khá darn hữu ích, thanks – fernandoespinosa