实体框架 - 仅更新不为空的值

问题描述 投票:0回答:3

这对我来说有点新鲜。我被要求编写一个 ETL 程序,将两个数据集加载到同一个表中。数据集 #1 已完成并包含表的所有数据。然而,数据集#2 仅包含需要覆盖到第一个数据集上的更改。观察:

// 数据集#1:小部件表

+----+------+------+------+------+
| ID | COL1 | COL2 | COL3 | COL4 |
+----+------+------+------+------+
| 1  | abcd | abcd | abcd | abcd |
+----+------+------+------+------+
| 2  | abcd | abcd | abcd | abcd |
+----+------+------+------+------+

// 数据集 #2:Widgets_Changes 表

+----+------+------+------+------+
| ID | COL1 | COL2 | COL3 | COL4 |
+----+------+------+------+------+
| 1  |      | efgh |      | ijkl |
+----+------+------+------+------+
| 2  | mnop |      | qrst |      |
+----+------+------+------+------+

// 预期结果:包含所有更改的小部件

+----+------+------+------+------+
| ID | COL1 | COL2 | COL3 | COL4 |
+----+------+------+------+------+
| 1  | abcd | efgj | abcd | ijkl |
+----+------+------+------+------+
| 2  | mnop | abcd | qrst | abcd |
+----+------+------+------+------+

显而易见的方法(我试图避免)是将每个小部件从第一个表中取出并进行逐个属性的比较:

// Simplified example:
using ( var db = new MyEntityDatabase() ){

   var widget      = from p in db.Widgets select p where p.ID == 1;
   var widget_diff = from p in db.Widgets_Changes select p where p.ID == 1

   widget.COL1 = widget_diff.COL1 ?? widget.COL1;
   widget.COL2 = widget_diff.COL2 ?? widget.COL2;
   widget.COL3 = widget_diff.COL3 ?? widget.COL3;
   // ...etc

   db.saveChanges();
}

但是,此特定数据集中有超过 200 个字段,传入的更多文件遵循相同的方法(完整数据集附带差异数据集),但具有完全不同的架构。

我想找到一种解决方案,避免对每个数据集进行硬编码逐个属性比较,但不确定如何实现。有没有办法迭代两个对象的属性并更新不为空的值?

c# linq entity-framework
3个回答
11
投票

首先,您需要使用类似的方法来选择要更新的实体:

var widget      = db.Widgets.First(p => p.ID == 1);
var widget_diff = db.Widgets_Changes.First(p => p.ID == 1);

现在您可以简单地使用反射来更新所有字段:

foreach(var toProp in typepf(Widget).GetProperties())
{
    var fromProp= typeof(Widget_Change).GetProperty(toProp.Name);
    var toValue = fromProp.GetValue(widget_diff, null);
    if (toValue != null)
    {
        toProp.SetValue(widget, toValue, null);
    }
}

通过预先构建属性列表可以加快速度,因此您只需使用反射一次:

public static class WidgetUtil
{
    public static readonly IEnumerable<Tuple<PropertyInfo, PropertyInfo>> PropertyMap;

    static Util()
    {
        var b = BindingFlags.Public | BindingFlags.Instance;
        PropertyMap = 
            (from f in typeof(Widget).GetProperties(b)
             join t in typeof(WidgetChange).GetProperties(b) on f.Name equals t.Name
             select Tuple.Create(f, t))
            .ToArray();
    }
}

...

foreach(var propertyPair in WidgetUtil.PropertyMap)
{
    var toValue = propertyPair.Item2.GetValue(widget_diff, null);
    if (toValue != null)
    {
        propertyPair.Item1.SetValue(widget, toValue, null);
    }
}

如果您有许多此类实体类型,您甚至可能需要考虑将其制作为通用实用程序:

public static class WidgetUtil<T1, T2>
{
    public static readonly IEnumerable<Tuple<PropertyInfo, PropertyInfo>> PropertyMap;

    static WidgetUtil()
    {
        var b = BindingFlags.Public | BindingFlags.Instance;
        PropertyMap = 
            (from f in typeof(T1).GetProperties(b)
             join t in typeof(T2).GetProperties(b) on f.Name equals t.Name
             select Tuple.Create(f, t))
            .ToArray();
    }
}

5
投票

您可能想为此使用反射。循环遍历每个小部件/差异的所有属性/字段,获取该属性/字段的值,如果差异为空,则使用原始值。

using(var db = new MyEntityDatabase())
{
    var widget      = from p in db.Widgets select p where p.ID == 1;
    var widget_diff = from p in db.Widgets_Changes select p where p.ID == 1;

    var properties = typeof(MyWidgetType).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    foreach(var property in properties)
    {
         //widget.column = widget_diff.column ?? widget.colum;
         property.SetValue(property.GetValue(widget_diff) ?? property.GetValue(widget), widget);
    }

    //You can do the same for fields here if the entity has any fields (probably not).
}

3
投票

@p.s.w.g 的答案很好,但是当我尝试实现它时,我遇到了几个错误(例如你无法使用 obj.Equals(null) 检查 null,null 没有 Equals 方法)。

这是 @p.s.w.g 很好的答案的“完整的可复制粘贴解决方案”(作为副产品)

静态泛型方法

InjectNonNull
获取要更新的源实体和带有空值的目标“稀疏”实体,并仅传输目标实体上的非空属性。

    private static class PropertyLister<T1, T2>
    {
        public static readonly IEnumerable<Tuple<PropertyInfo, PropertyInfo>> PropertyMap;

        static PropertyLister()
        {
            var b = BindingFlags.Public | BindingFlags.Instance;
            PropertyMap =
                (from f in typeof(T1).GetProperties(b)
                 join t in typeof(T2).GetProperties(b) on f.Name equals t.Name
                 select Tuple.Create(f, t))
                    .ToArray();
        }
    }


    public static T InjectNonNull<T>(T dest, T src)
    {
        foreach (var propertyPair in PropertyLister<T, T>.PropertyMap)
        {
            var fromValue = propertyPair.Item2.GetValue(src, null);
            if (fromValue != null && propertyPair.Item1.CanWrite)
            {

                propertyPair.Item1.SetValue(dest, fromValue, null);
            }
        }

        return dest;
    }
© www.soinside.com 2019 - 2024. All rights reserved.