2011-05-02 67 views
1

我有以下代碼從第三方下載對象,我想將插入/更新保存到我的數據庫中。該模型中有10個由SQL Server創建的表,這些表是從SOAP對象中生成的。爲了簡單起見,我創建了以下示例以僅顯示單個子表(但實際上有幾個圖層MyTable - > MyTableChild - > MyTableGrandChild),因此我們可以假設我有一個MyTable EntityType和一個MyTableChild EntityType,其中存在一個EntityCollection包含在MyTable中的MyTableChild對象。從另一個對象更新EntityType中的EntityCollection

using (Model.MyEntities context = new Model.MyEntities()) 
{ 
    var MyObjectsFromSQL = from a in context.MyTable select a; 

    [AutoMapper][1].CreateMap<SOAPChildObject, Model.MyTableChild>(); 
    [AutoMapper][2].Mapper.CreateMap<SOAPObject, Model.MyTable>(); 
    var DownloadedObjects = Mapper.Map<SOAPObject[], IEnumerable<Model.MyTable>>(ArrayOfSOAPObjects); 

    foreach (var DownloadedObject in DownloadedObjects) 
    { 
     Model.MyTable CurrentObject = context.MyTable.Where(a => a.key == D2.key).Single(); 
     // How do I check the changes in the DownloadedObject against 
     // the MyObjectsFromSQL so I can send the changes back to SQL 
    } 
    context.SaveChanges(); 
} 

我已經嘗試了各種東西,但什麼是有意義的我是努力值從DownloadedObject到CurrentObject複製並讓框架做它的魔力。這似乎適用於非EntityCollection成員,但給了我EntityCollections的錯誤。

MyObjectsFromSQL.MyStringObject = DownloadedObject.MyStringObject 
MyObjectsFromSQL.MyTableChildObject = DownloadedObject.MyTableChildObject; // ERROR: System.InvalidOperationException! 

System.InvalidOperationException was unhandled 
Message=The EntityCollection has already been initialized. The InitializeRelatedCollection method should only be called to initialize a new EntityCollection during deserialization of an object graph. 
Source=System.Data.Entity 
StackTrace: 
    at System.Data.Objects.DataClasses.RelationshipManager.InitializeRelatedCollection[TTargetEntity](String relationshipName, String targetRoleName, EntityCollection`1 entityCollection) 
    at Model.MyTable.set_MyTableChild(EntityCollection`1 value) 

回答

3

實體框架不能自動比較相關對象的集合,所以你需要自己做這個邏輯。

,而不是設置MyObjectsFromSQL.MyTableChildObject = DownloadedObject.MyTableChildObject;,你會需要比較藏品件逐件,並稱不存在MyObjectsFromSQL.MyTableChildObject尚品,除去沒有出現在DownloadedObject.MyTableChildObject項目,並更新標量值每個項目都存在於兩者中。

同樣,如果子對象具有其他子對象,則需要遞歸地遵循相同的模式。

相關問題