如何从 ChangeTracker 获取原始实体 [英] How to get original Entity from ChangeTracker

查看:16
本文介绍了如何从 ChangeTracker 获取原始实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

If the State is Modified, then I suppose I could do this:

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

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

But this doesn't seem very nice, and I'm sure there are problems with it that I don't know about... Is there a better way?

我正在使用实体框架 6.

I'm using Entity Framework 6.

推荐答案

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

Override SaveChanges of DbContext or just access ChangeTracker from the context:

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

<小时>

这是一个使用原始值创建新实体的方法.因此所有实体都应该有一个无参数的公共构造函数,你可以简单地用 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;
}

这篇关于如何从 ChangeTracker 获取原始实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆