samedi 26 septembre 2015

how to get the property name after by comparing it with a string name in EF6

I am developing an MVC 5 application and I needed to maintain a log of all the changes so I get the following function to make a list of all changes happened to a document at the time of submission. It get the original entities and modified as parameter and then return which values are changed by what.

public static IEnumerable<KeyValuePair<string, object>> ModifiedValues<T>(this T obj, T modifiedObject)
{
     foreach (var property in typeof(T).GetProperties().Where(p => !p.GetGetMethod().IsVirtual))
     {
          if (property.GetValue(obj) != null && property.GetValue(modifiedObject) != null)
          {
               if (!(property.GetValue(obj).ToString() == property.GetValue(modifiedObject).ToString()))
               {
                    yield return new KeyValuePair<string, object>(property.Name, property.GetValue(modifiedObject));
               }
          }             
     }
}

Now, it returns the name of the changed property as string and the new value as an object. Now I want to get the original value from the database only against the changed property but the problem is that changed property name is a string. I am calling the method as:

var originalEntity = db.ABCs.AsNoTracking().FirstOrDefault(e => e.Id == v.Id);
var modifiedValues = originalEntity.ModifiedValues<ABC>(t).ToList(); // t holds the modified values of the entity

Let me put this with example:

If my number on a document was 123456 and then I changed it to 456789, the function above will return the property name "PhoneNo" as a string and the new value (456789) as an object. Now I want to query the database for "PhoneNo" property only to get the original value(123456) before writing the new one to database, to maintain a log. Since, I cannot recall any method to query a property name, when the property name is a string type.

How can I do it?





Aucun commentaire:

Enregistrer un commentaire