How to get original Entity from ChangeTracker(如何从 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?
我正在使用实体框架 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 获取原始实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 ChangeTracker 获取原始实体


基础教程推荐
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01