本文介绍了如何从ChangeTracker获取原始实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以从ChangeTracker
获取原始实体本身(而不仅仅是原始值)?
Is there a way to get the original Entity itself from the ChangeTracker
(rather than just the original values)?
如果State
是Modified
,那么我想我可以这样做:
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?
我正在使用Entity Framework 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获取原始实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!