Is there a way to get the original Entity itself from the ChangeTracker
(rather than just the original values)?
If the State
is Modified<
Nice. Here is a slightly modified version that will handle complex properties:
public static TEntity GetOriginal(this DbContext ctx, TEntity updatedEntity) where TEntity : class
{
Func getOriginal = null;
getOriginal = (originalValues, type) =>
{
object original = Activator.CreateInstance(type, true);
foreach (var ptyName in originalValues.PropertyNames)
{
var property = type.GetProperty(ptyName);
object value = originalValues[ptyName];
if (value is DbPropertyValues) //nested complex object
{
property.SetValue(original, getOriginal(value as DbPropertyValues, property.PropertyType));
}
else
{
property.SetValue(original, value);
}
}
return original;
};
return (TEntity)getOriginal(ctx.Entry(updatedEntity).OriginalValues, typeof(TEntity));
}