Obtaining all Entity Framework updates made to an object

c# entity-framework


Is it possible to get all the modifications made to an object in the Entity Framework prior to the changes being saved? This is necessary since I want to build a log table in our client's database:


Is it possible to get both the previous and present database values before modifications are saved?

If not, how can I do this such that all of my view models may derive from it? (I'm using MVVM + M Structure)

7/16/2010 1:25:18 PM

Accepted Answer

The ObjectStateEntry of an object, which is stored in the OriginalValues and CurrentValues properties, may be obtained using the ObjectContext's ObjectStateManager,GetObjectStateEntry. The GetModifiedProperties technique may be used to get the names of the properties that have changed.

You may put it like this:

var myObjectState=myContext.ObjectStateManager.GetObjectStateEntry(myObject);
var modifiedProperties=myObjectState.GetModifiedProperties();
foreach(var propName in modifiedProperties)
    Console.WriteLine("Property {0} changed from {1} to {2}", 
10/25/2016 1:19:57 AM

Popular Answer

As of EF5, you may record your modifications using the SaveChanges() function as follows:

    public override int SaveChanges()

        var changes = from e in this.ChangeTracker.Entries()
                      where e.State != System.Data.EntityState.Unchanged
                      select e;

        foreach (var change in changes)
            if (change.State == System.Data.EntityState.Added)
                // Log Added
            else if (change.State == System.Data.EntityState.Modified)
                // Log Modified
                var item = change.Cast<IEntity>().Entity;
                var originalValues = this.Entry(item).OriginalValues;
                var currentValues = this.Entry(item).CurrentValues;

                foreach (string propertyName in originalValues.PropertyNames)
                    var original = originalValues[propertyName];
                    var current = currentValues[propertyName];

                    if (!Equals(original, current))
                        // log propertyName: original --> current

            else if (change.State ==  System.Data.EntityState.Deleted)
                // log deleted
        // don't forget to save

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow