【发布时间】:2012-02-29 16:56:13
【问题描述】:
简单地说,我有一个实体框架将两个表映射到对象: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 本身有对其他实体的引用呢?)。
但是,我想知道:这(整个过程或部分过程)是否可以更轻松地完成?不,我不能从项目中删除所有属性并在更新时重新添加它们,因为我想保留这些实体中的其他数据。
【问题讨论】:
标签: c# entity-framework