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

时间:2012-02-29 16:56:13

标签: c# entity-framework

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

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

我找到了各种related questionsanswers(其中并非所有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.Propertiesp.Name == existingProp.Namep.ItemID == existingItem.ID)有各种引用,但是可以构建此方法的更通用版本,甚至可能在一个小的递归中摆弄(如果Property本身有对其他实体的引用会怎么样?)。

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

1 个答案:

答案 0 :(得分:3)

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

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