How to get original Entity from ChangeTracker

前端 未结 4 1978
执笔经年
执笔经年 2021-02-04 11:50

Is there a way to get the original Entity itself from the ChangeTracker (rather than just the original values)?

If the State is Modified<

4条回答
  •  Happy的楠姐
    2021-02-04 12:29

    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));
        }
    

提交回复
热议问题