views:

52

answers:

2

Is there a way to get all the changes made to a object in the Entity Framework before it saves all changes. The reason for this is that i want to create a log table in our clients database:

so...

Is there a way to get the current database values(old) and the new values(current) before changes are saved?

If not, how can i achieve this in a generic way, so all my View Models can inherit from this?(I am using the MVVM + M Structure)

A: 

You could read the object from the source (the database) just before saving and compare field by field with the object you want to save.

If you want to do it generic use reflection to get the fields to compare, this way you can write a method to do the comparison without knowing the exact object you want to compare.

despart
+5  A: 

You can use ObjectContext's ObjectStateManager,GetObjectStateEntry to get an object's ObjectStateEntry, which hold its original and current values in the OriginalValues and CurrentValues properties. You can get the names of the properties that changed using the GetModifiedProperties method

You can right something like:

var myObjectState=myContext.ObjectStateManager.GetObjectStateEntry(myObject);
var modifiedProperties=myObjectState.GetModifiedProperties();
foreach(var propName in modifiedProperties)
{
    Console.WriteLine("Property {0} changed from {1} to {2}", 
         propName,
         myObjectState.CurrentValues[propName],
         myObjectState.OriginalValues[propName]);
}
Panagiotis Kanavos