发现相同类型的两个实体之间的差异 [英] Find differences between two entities of the same type
问题描述
我工作的一个MVC3 Web应用程序。当用户更新的东西,我要旧数据比较到新用户输入查询和该不同的是加入这些到日志来创建活动日志的每个字段。
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,名称,状态...),这些属性不是值(1,你好,准备好...)。
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...).
我可以只去硬盘的方式:
I could just go the hard way:
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;
}
}
这篇关于发现相同类型的两个实体之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!