2010-07-22 127 views
0

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

这个想法是你将数据下载为一个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在同一台服务器上,但我想这个问题仍然是相同的。

回答

1

你在谈论一个n层的情况。

请参阅building n-tier applications with EFattaching and detaching objects

只要调用Attach就是告诉EF该对象没有改变。

如果它是一个新的对象(例如,你知道它的插件和更新操作),那么你应该叫AddObject代替Attach,就大功告成了。但是,如果XML代表对可能存在的对象的一些更改,那么您需要做更多工作(有关详细信息,请参阅MSDN页面)。