[英]How can I detect changes to properties in a specific entity in Entity Framework Core 2.x?
When a user saves changes to an object myObject
, I'd like to log the fields that were updated to that object.当用户保存对对象
myObject
更改时,我想记录更新到该对象的字段。
I can get an object with我可以得到一个对象
var myObject = await context.MyObjects.SingleAsync(x => x.Id == id);
And I see that I can get an IEnumerable<PropertyEntry>
with我看到我可以得到一个
IEnumerable<PropertyEntry>
var changes = context.Entry(myObject).Properties.Where(x => x.IsModified);
But in my changes
list I don't see the field name anywhere.但是在我的
changes
列表中,我在任何地方都看不到字段名称。 Also, it seems to take 2 full seconds to make this members query in LINQPad.此外,在 LINQPad 中使这个成员查询似乎需要整整 2 秒。 That doesn't seem right.
这似乎不对。
How do I complete the following statement?我如何完成以下陈述?
Consolse.Write($"The field {what goes here?} was updated from {change.OriginalValue} to {change.CurrentCalue}.");
Other StackOverflow questions I've found are for previous versions of Entity Framework, or override SaveChanges
and don't look for specific entities.我发现的其他 StackOverflow 问题是针对以前版本的实体框架,或者覆盖
SaveChanges
并且不查找特定实体。
Update!更新! Got it.
知道了。
public string GetChangeLog<T>(
ApplicationDbContext context,
T entity)
{
var sb = new StringBuilder();
var changes = context.Entry(entity).Properties.Where(x => x.IsModified);
foreach (var change in changes)
{
var propertyBase = (IPropertyBase)change.Metadata;
sb.Append($"\"{propertyBase.Name}\" was changed from \"{change.OriginalValue}\" to \"{change.CurrentValue}\"\n");
}
return sb.ToString();
}
Use the .Metadata
property to retrieve a IPropertyBase
.使用
.Metadata
属性来检索IPropertyBase
。 That will tell you what has actually changed.这将告诉您实际发生了什么变化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.