Getting all changes made to an object in the Entity Framework

Viewed 63027

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)

4 Answers

Use the IsModified field of each property, which is accessible by Context.Entry(Entity).Properties.

In this example, the modified entries are listed as a Tuple of the original and current values, indexed by name. Use any conversion that is required to build the audit log.

using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;

//...

// gets somewhere in the scope
DbContext Context;
// Some entity that has been modified, but not saved and is being tracked by Context
object Entity;

//...

Dictionary<string, System.Tuple<object, object>> modified = 
    Context.Entry(Entity)
        .Properties.Where(p => p.IsModified)
        .ToDictionary(p => p.Metadata.Name, 
                      p => new System.Tuple<object,object>(p.OriginalValue, p.CurrentValue));
//...

Uses Entity Framework Core 3.1. Try it for EF 6.4, but it may not work.

Related