Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 使用实体框架跨数据库复制数据_.net_Frameworks_Entity - Fatal编程技术网

.net 使用实体框架跨数据库复制数据

.net 使用实体框架跨数据库复制数据,.net,frameworks,entity,.net,Frameworks,Entity,我试图使用实体框架从一个数据库中获取数据(嵌套关系),并将其插入到另一个数据库中 其思想是将数据下载为XML文件,然后将其上载,并将其插入新的数据库中 下载到XML很简单: var BoroughQuery = from b in Context.Borough.Include("User").Include("Location").Include("Contact").Include("Location.LocationContact") where b.Id == BoroughId sel

我试图使用实体框架从一个数据库中获取数据(嵌套关系),并将其插入到另一个数据库中

其思想是将数据下载为XML文件,然后将其上载,并将其插入新的数据库中

下载到XML很简单:

var BoroughQuery = from b in Context.Borough.Include("User").Include("Location").Include("Contact").Include("Location.LocationContact") where b.Id == BoroughId select b;

BoroughModel = BoroughQuery.First();

Context.Detach(BoroughModel);

System.Runtime.Serialization.DataContractSerializer ser = new System.Runtime.Serialization.DataContractSerializer(typeof(Borough));
System.IO.DirectoryInfo TempDirectory = new System.IO.DirectoryInfo(Server.MapPath(Request.ApplicationPath + "Temp"));
if (!TempDirectory.Exists) TempDirectory.Create();
System.IO.FileInfo TempFile = new System.IO.FileInfo(TempDirectory.FullName + "\\" + BoroughModel.Key + "_" + System.DateTime.UtcNow.ToString("yyyyMMddhhmmss") + ".xml");
FileStream writer = new FileStream(TempFile.FullName, FileMode.Create);
ser.WriteObject(writer, BoroughModel);
writer.Close();
问题 …正在将读取的XML附加到另一个上下文并将其保存到数据库

到目前为止,我有以下内容,可以从XML精细地读入模型,但不会将任何内容添加到数据库中:

DataContractSerializer ser = new DataContractSerializer(typeof(Borough));
Borough deserializedBorough = (Borough)ser.ReadObject(fleBoroughUpload.FileContent);

using (Entities Context = new Entities("name=EntitiesTarget"))
{
    Context.Attach(deserializedBorough);
    Context.SaveChanges();
}
任何帮助都将不胜感激

注意
因为这两个数据库都在同一台服务器上,所以数据不必以XML的形式出现,但我认为问题仍然是一样的。

您所说的是n层情况

见和

只需调用
Attach
就可以告诉EF对象没有更改

如果它是一个新对象(例如,您知道它是一个插入操作,而不是一个更新操作),那么您应该调用
AddObject
,而不是
Attach
,您就完成了。但是,如果XML表示对可能存在的对象的某些更改集,那么您还有更多的工作要做(有关详细信息,请参阅MSDN页面)