Home > Software engineering >  In Entity Framework, how can I see changes before saving?
In Entity Framework, how can I see changes before saving?

Time:01-05

Is there a method to call in Entity Framework to see the data that has changed (in memory) and would be written to disk when SaveChanges is called?

I'd like to display something to the user indicating that there is an unsaved change. Table level is ok, but I'd prefer to know if a particular field/column has an unsaved change.

CodePudding user response:

For example, add this method to your context:

IEnumerable<(string Key, string Entity, EntityState state,
    IEnumerable<(string Property, object OriginalValue, object CurrentValue)> Properties)> GetChanges()
{
    var states = new[] { EntityState.Added, EntityState.Modified, EntityState.Deleted };
    return this.ChangeTracker.Entries().Where(c => states.Contains(c.State))
        .Select(entry =>
            (
                string.Join(",", entry.Metadata.FindPrimaryKey()
                    .Properties.Select(p => p.PropertyInfo.GetValue(entry.Entity))),
                entry.Metadata.ClrType.Name,
                entry.State,
                entry.Properties
                    .Where(p => p.IsModified == (p.EntityEntry.State == EntityState.Modified))
                    .Select(prop =>
                    (
                        prop.Metadata.PropertyInfo.Name, 
                        prop.OriginalValue, 
                        prop.CurrentValue
                    )
            )));
}

It returns added, modified or deleted entity objects, listing their class names (not table names) and their properties, with original and current values. The key values are also included to be able to make a distinction between objects of the same type.

Of modified entities only the changed properties are listed.

CodePudding user response:

Simply enumerate the ChangeTracker.Entries to examine all the tracked entities, and their EntityEntry.State.

  •  Tags:  
  • Related