c# - 如何从 ChangeTracker 获取原始实体

标签 c# .net entity-framework entity-framework-6

有没有办法从 ChangeTracker 中获取原始实体本身(而不仅仅是原始值)?

如果 StateModified,那么我想我可以这样做:

// Get the DbEntityEntry from the DbContext.ChangeTracker...

// Store the current values
var currentValues = entry.CurrentValues.Clone();

// Set to the original values
entry.CurrentValues.SetValues(entry.OriginalValues.Clone());

// Now we have the original entity
Foo entity = (Foo)entry.Entity;

// Do something with it...

// Restore the current values
entry.CurrentValues.SetValues(currentValues);

但这看起来不太好,而且我确定它存在我不知道的问题......有没有更好的方法?

我正在使用 Entity Framework 6。

最佳答案

覆盖 DbContext 的 SaveChanges 或仅从上下文访问 ChangeTracker:

foreach (var entry in context.ChangeTracker.Entries<Foo>())
{
    if (entry.State == System.Data.EntityState.Modified)
    {
        // use entry.OriginalValues
        Foo originalFoo = CreateWithValues<Foo>(entry.OriginalValues);
    }
}

这是一个使用原始值创建新实体的方法。因此所有的实体都应该有一个无参数的公共(public)构造函数,你可以简单地用 new 构造一个实例:

private T CreateWithValues<T>(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<object>(name));
    }

    return entity;
}

关于c# - 如何从 ChangeTracker 获取原始实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15012621/

相关文章:

c# - 在 C# 控制台应用程序中使用 Windows 8 API (VideoCaptureDevices)

c# - 使用 SharpZipLib 压缩大文件导致内存不足异常

c# - 寻找集体智慧 .Net/C# 资源

.net - Entity Framework 4与NHibernate

c# - Entity Framework 6.1.1 禁用模型兼容性检查

c# - 无法在 Windows 7 中使用 C# 中的窗口服务计算系统空闲值

c# - 如果我调用在未执行的函数内声明的事件处理程序,会发生什么情况?

C# 定时器回调

c# - Npgsql 奇怪的异常

c# - Entity Framework 外键引用不映射