使用EF从两个数据库之间复制记录 [英] copy records from between two databases using EF

查看:86
本文介绍了使用EF从两个数据库之间复制记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用EF将数据从一个数据库复制到另一个数据库。例如。我有以下表格关系:Forms-> FormVersions-> FormLayouts ...我们在两个数据库中都有不同的表单,我们希望将它们收集到一个数据库。基本上,我想从一个DB递归加载Form对象,并将其保存到具有所有引用的另一个DB。此外,如果存在第二个数据库中具有相同ID的对象,我还需要更改对象和相关对象的ID。



到现在为止,我有以下代码:

  Form form = null ; 
using(var context = new FormEntities())
{
form =(from f in context.Forms
join fv in context.FormVersions on f.ID equals fv.FormID
其中f.ID == 56
选择f).First();
}

var context1 = new FormEntities(name = FormEntities1);
context1.AddObject(Forms,form);
context1.SaveChanges();

我收到错误:EntityKey属性只能在当前值属性为null。



您可以帮助实现吗?

解决方案

最简单的解决方案是创建Form(新对象)的副本,并添加新对象。否则你可以尝试:


  1. 调用 context.Detach(form)

  2. 设置表单的 EntityKey 为null

  3. 调用 context1.AddObject(form)


I need to copy data from one database to another with EF. E.g. I have the following table relations: Forms->FormVersions->FormLayouts... We have different forms in both databases and we want to collect them to one DB. Basically I want to load Form object recursively from one DB and save it to another DB with all his references. Also I need to change IDs of the object and related objects if there are exists objects with the same ID in the second database.

Until now I have following code:

Form form = null;
using (var context = new FormEntities())
        {
            form = (from f in context.Forms
                        join fv in context.FormVersions on f.ID equals fv.FormID
                        where f.ID == 56
                        select f).First();
        }

        var context1 = new FormEntities("name=FormEntities1");
        context1.AddObject("Forms", form);
        context1.SaveChanges();

I'm receiving the error: "The EntityKey property can only be set when the current value of the property is null."

Can you help with implementation?

解决方案

The simplest solution would be create copy of your Form (new object) and add that new object. Otherwise you can try:

  1. Call context.Detach(form)
  2. Set form's EntityKey to null
  3. Call context1.AddObject(form)

这篇关于使用EF从两个数据库之间复制记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆