Willem Willem - 5 months ago 58
C# Question

Getting all changes made to an object in the Entity Framework

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:


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)


You can use ObjectContext's ObjectStateManager,GetObjectStateEntry to get an object's ObjectStateEntry, which holds 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 write 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}",