查找相同类型的两个实体之间的差异

查找相同类型的两个实体之间的差异

本文介绍了查找相同类型的两个实体之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 mvc3 网络应用程序.当用户更新某些内容时,我想将旧数据与用户输入的新数据进行比较,并将每个不同的字段添加到日志中以创建活动日志.

I'm working on an mvc3 web app. When the user updates something, I want to compare the old data to the new one the user is inputing and for each field that is different add those to a log to create an activity log.

现在这就是我的保存操作的样子:

Right now this is what my save action looks like:

[HttpPost]
public RedirectToRouteResult SaveSingleEdit(CompLang newcomplang)
{
    var oldCompLang = _db.CompLangs.First(x => x.Id == newcomplang.Id);

    _db.CompLangs.Attach(oldCompLang);
    newcomplang.LastUpdate = DateTime.Today;
    _db.CompLangs.ApplyCurrentValues(newcomplang);
    _db.SaveChanges();

    var comp = _db.CompLangs.First(x => x.Id == newcomplang.Id);

    return RedirectToAction("ViewSingleEdit", comp);
}

我发现我可以用它来遍历我的 oldCompLang 属性:

I found that I could use this to iterate through my property of oldCompLang:

var oldpropertyInfos = oldCompLang.GetType().GetProperties();

但这并没有真正的帮助,因为它只向我显示属性(Id、Name、Status...)而不是这些属性的值(1、Hello、Ready...).

But this doesn't really help as it only shows me the properties (Id, Name, Status...) and not the values of these properties (1, Hello, Ready...).

我只能硬着头皮走:

if (oldCompLang.Status != newcomplang.Status)
{
    // Add to my activity log table something for this scenario
}

但我真的不想对对象的所有属性都这样做.

But I really don't want to be doing that for all the properties of the object.

我不确定遍历两个对象以查找不匹配项的最佳方法是什么(例如,用户更改了名称或状态...)并从这些差异中构建了一个列表,我可以将其存储在另一个表中.

I'm not sure what's the best way to iterate through both objects to find mismatches (for example the user changed the name, or the status...) and build a list from those differences that I can store in another table.

推荐答案

还不错,您可以使用反射手动"比较属性并编写扩展方法以供重用 - 您可以以此为起点:

It's not that bad, you can compare the properties "by hand" using reflection and write an extension methods for reuse - you can take this as a starting point:

public static class MyExtensions
{
    public static IEnumerable<string> EnumeratePropertyDifferences<T>(this T obj1, T obj2)
    {
        PropertyInfo[] properties = typeof(T).GetProperties();
        List<string> changes = new List<string>();

        foreach (PropertyInfo pi in properties)
        {
            object value1 = typeof(T).GetProperty(pi.Name).GetValue(obj1, null);
            object value2 = typeof(T).GetProperty(pi.Name).GetValue(obj2, null);

            if (value1 != value2 && (value1 == null || !value1.Equals(value2)))
            {
                changes.Add(string.Format("Property {0} changed from {1} to {2}", pi.Name, value1, value2));
            }
        }
        return changes;
    }
}

这篇关于查找相同类型的两个实体之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 11:17