Asp.net-Mvc
查找相同類型的兩個實體之間的差異
我正在開發一個 mvc3 網路應用程序。當使用者更新某些內容時,我想將舊數據與使用者輸入的新數據進行比較,並將每個不同的欄位添加到日誌中以創建活動日誌。
現在這就是我的保存操作的樣子:
[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 屬性:
var oldpropertyInfos = oldCompLang.GetType().GetProperties();但這並沒有真正的幫助,因為它只顯示屬性(Id、Name、Status…)而不是這些屬性的值(1、Hello、Ready…)。
我只能走艱難的路:
if (oldCompLang.Status != newcomplang.Status) { // Add to my activity log table something for this scenario }但我真的不想對對象的所有屬性都這樣做。
我不確定遍歷這兩個對像以查找不匹配(例如使用者更改了名稱或狀態…)並從我可以儲存在另一個表中的那些差異建構一個列表的最佳方法是什麼。
這還不錯,您可以使用反射“手動”比較屬性並編寫擴展方法以供重用 - 您可以以此為起點:
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; } }