How to get original Entity from ChangeTracker

前端 未结 4 1935
执笔经年
执笔经年 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条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-04 12:26

    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(name));
        }
    
        return entity;
    }
    
        

    提交回复
    热议问题