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);
}
I found that I could use this to iterate through my property of oldCompLang:
var oldpropertyInfos = oldCompLang.GetType().GetProperties();
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.