【问题标题】:Adding, removing and updating related entities添加、删除和更新相关实体
【发布时间】:2012-02-29 16:56:13
【问题描述】:

简单地说,我有一个实体框架将两个表映射到对象: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 本身有对其他实体的引用呢?)。

但是,我想知道:这(整个过程或部分过程)是否可以更轻松地完成?不,我不能从项目中删除所有属性并在更新时重新添加它们,因为我想保留这些实体中的其他数据。

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    作为开发人员,您的工作是编写代码 :),这不是“大量代码”。

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

    【讨论】:

    • 作为一名开发人员,我的工作是不断思考“这是否可以以更好的方式完成?”,这就是我的问题。 ;-) 我希望有一种更通用的方法,最好内置在 EF 中,因为正如我所说,这是一个简化的示例,我不想继续重复我的代码。
    • No EF 不包含任何内置机制来解决这个问题 - here 是我的分析。
    • 我已经找到了那个很棒的帖子,现在我发现我忘记在我的问题中链接到它了。还是谢谢。
    猜你喜欢
    • 1970-01-01
    • 2018-06-29
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    • 1970-01-01
    相关资源
    最近更新 更多