Why do the original values of a DbEntityEntry match the new values?

admin

Administrator
Staff member
I am attempting to implement auditing in my MVC 4 with EF application as per this post <a href="http://jmdority.wordpress.com/2011/...-dbcontext-change-tracking-for-audit-logging/" rel="nofollow">http://jmdority.wordpress.com/2011/...-dbcontext-change-tracking-for-audit-logging/</a>.

I am having trouble finding the changed properties when an entity is modified. I have a class that inherits from DbContext and overrides the SaveChanges method. In this new SaveChanges method I have the following code to look for changed properties, where entity is from ChangeTracker.Entities().

Code:
foreach (var propertyName in entity.OriginalValues.PropertyNames)
{
    var originalValue = entity.OriginalValues.GetValue&lt;object&gt;(propertyName);
    var newValue = entity.CurrentValues.GetValue&lt;object&gt;(propertyName);

    if (!object.Equals(originalValue, newValue))
    {
        // Insert an auditing record.
    }
}

This issue is that the originalValue is always equal to the newValue, even though nothing has been saved to the database yet. How can I get the original value so I can check if the property has changed?

Thanks in advance!