添加,删除和更新相关实体

简化,我有一个entity framework将两个表映射到对象: ItemsProperties 。 每个项目都有一定的属性(一对多)。

从我的程序外部,我收到带有属性的“死”项,这些属性是新项或现有项的更新及其属性。 这个数据可能来自WCF调用,Web表单POST,反序列化:我要点插入并更新数据库中的项目和属性,以及我收到的未链接数据。

我发现了各种相关的问题和答案 (其中甚至都没有编译 )。 问题是我必须编写大量代码来同步现有项的属性和传入的更新项:

 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.Propertiesp.Name == existingProp.Namep.ItemID == existingItem.ID ),但它可以构建一个更通用的版本方法,甚至可能在一个小的递归中摆弄(如果一个Property本身有对其他实体的引用怎么办?)。

但是,我想知道:这个(整个过程,或者它的一部分)能够更容易地完成吗? 不,我无法删除项目中的所有属性并在更新时重新添加它们,因为我想要保留的那些实体中还有其他数据。

作为开发人员,编写代码是你的工作:)这不是“很多代码”。

没有全局通用方法来处理此代码。 您可以找到一种方法来概括您的样本,但它仍然只针对特定的案例集进行定制。 您的简单方法包含许多与ItemProperty类紧密耦合的代码。 推广此代码需要注入处理方法之外的这些依赖项的委托或表达式。