Is there a way to get the original Entity itself from the ChangeTracker
(rather than just the original values)?
If the State
is Modified<
Override SaveChanges
of DbContext or just access ChangeTracker
from the context:
foreach (var entry in context.ChangeTracker.Entries())
{
if (entry.State == System.Data.EntityState.Modified)
{
// use entry.OriginalValues
Foo originalFoo = CreateWithValues(entry.OriginalValues);
}
}
Here is a method which will create a new entity with the original values. Thus all entities should have a parameterless public constructor, you can simply construct an instance with new
:
private T CreateWithValues(DbPropertyValues values)
where T : new()
{
T entity = new T();
Type type = typeof(T);
foreach (var name in values.PropertyNames)
{
var property = type.GetProperty(name);
property.SetValue(entity, values.GetValue