2010-07-22 64 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頁面)。