使用Entity Framework在数据库之间复制实体

时间:2021-05-24 09:45:42

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

有两个具有相同模式的独立数据库,我需要使用Entity Framework 4将实体(记录)从一个数据库复制到另一个数据库。

I'm creating 2 Contexts, but I'm getting the following error when I add one entity to the second Context:

我正在创建2个上下文,但是当我向第二个上下文添加一个实体时,我收到以下错误:

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

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

我知道如果我使用Detach方法可以避免该错误,但在这种情况下相关实体会丢失!

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

How can I perform such operation? Alternatively, how can I detach the entity without losing the related entities?

我该如何进行这样的操作?或者,如何在不丢失相关实体的情况下分离实体?

2 个解决方案

#1


8  

For once the error message is helpful - entities can only belong to one context at a time. To do what you're wanting you'll need to Detatch each entity from the first context before adding it to the second.

一旦错误消息有用 - 实体一次只能属于一个上下文。要做你想要的事情,你需要从第一个上下文中删除每个实体,然后再将它添加到第二个上下文中。

Like you said, this will kill related entities. Unfortunately you'll have to deal with this (annoying) aspect of Detach.

就像你说的,这将杀死相关实体。不幸的是,你将不得不处理Detach的这个(恼人的)方面。

#2


5  

For future reference, the following article helped me:

为了将来参考,以下文章帮助我:

Cloning the Entity object and all related children using the Entity Framework

使用实体框架克隆Entity对象和所有相关子代

#1


8  

For once the error message is helpful - entities can only belong to one context at a time. To do what you're wanting you'll need to Detatch each entity from the first context before adding it to the second.

一旦错误消息有用 - 实体一次只能属于一个上下文。要做你想要的事情,你需要从第一个上下文中删除每个实体,然后再将它添加到第二个上下文中。

Like you said, this will kill related entities. Unfortunately you'll have to deal with this (annoying) aspect of Detach.

就像你说的,这将杀死相关实体。不幸的是,你将不得不处理Detach的这个(恼人的)方面。

#2


5  

For future reference, the following article helped me:

为了将来参考,以下文章帮助我:

Cloning the Entity object and all related children using the Entity Framework

使用实体框架克隆Entity对象和所有相关子代