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 获取原始实体
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
