簡化,我有一個實體框架將兩個表映射到對象:Items
和Properties
。每個項目都有一定的屬性(一對多)。添加,刪除和更新相關實體
從我的程序外部,我收到帶有屬性的「已死」項目,這些屬性是新項目或現有項目的更新及其屬性。這些數據可能來自WCF調用,Web表單POST和反序列化:關鍵是我想插入並更新數據庫中的項目和屬性,並使用我獲得的未鏈接數據。
我發現各種related questions和answers(這不是全部even compile)。問題是我必須寫的代碼加載到現有的項目和傳入,更新項目的屬性同步:
private static void UpdateProperties(Item existingItem, Item updatedItem, TestdatabaseEntities context)
{
// Find deleted properties
foreach (var existingProp in existingItem.Properties.ToList()) // ToList() to work on a local copy, otherwise you'll be removing items from an enumeration
{
var inUpdate = updatedItem.Properties.Where(p => p.Name == existingProp.Name).FirstOrDefault();
if (inUpdate == null)
{
// Property with this Name was not found as property in the updated item, delete it
context.Properties.DeleteObject(existingProp);
}
}
// Find added or updated properties
foreach (var updatedProp in updatedItem.Properties)
{
var inDatabase = existingItem.Properties.Where(p => p.ItemID == existingItem.ID && p.Name == updatedProp.Name).FirstOrDefault();
if (inDatabase == null)
{
// Added
inDatabase = new Property { Name = updatedProp.Name };
existingItem.Properties.Add(inDatabase);
}
// Updated (& added), map properties (could be done with something like AutoMapper)
inDatabase.Value = updatedProp.Value;
// etc...
}
context.SaveChanges();
}
你看,有向(對象的特定屬性existingItem.Properties
,p.Name == existingProp.Name
各種參考, p.ItemID == existingItem.ID
),但是建立這個方法的更通用的版本是可行的,甚至可能在小的遞歸中擺弄(如果一個Property
本身具有對其他實體的引用呢?)。
但是,我想知道:這可以(整個過程,或其中的一部分)更容易完成嗎?不,我無法刪除項目中的所有屬性,並在更新時重新添加它們,因爲我想保留這些實體中的其他數據。
你所描述的問題聽起來像一個對象映射練習。如果我已經正確理解你,你可能會發現http://automapper.org/有幫助。 – Robert 2012-07-31 09:17:46
@Robert映射不是問題(請參閱'inDatabase.Value'行上面的註釋),但是如何將分離項與附加項進行比較,並在需要時以更優雅的方式更新後者。 – CodeCaster 2012-07-31 09:20:41
我很喜歡這個問題,當我不同意別人的錯誤答案,並嘗試在評論中解釋這個問題時,這個問題有時會隨機得到低估。請繼續這樣做,這些2分扣除每次都會傷害很多。 – CodeCaster 2013-05-15 07:41:21