我有以下代碼從第三方下載對象,我想將插入/更新保存到我的數據庫中。該模型中有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)