Reputation: 10627
When a user saves changes to an object myObject
, I'd like to log the fields that were updated to that object.
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
var changes = context.Entry(myObject).Properties.Where(x => x.IsModified);
But in my changes
list I don't see the field name anywhere. Also, it seems to take 2 full seconds to make this members query in LINQPad. 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.
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();
}
Upvotes: 3
Views: 1984
Reputation: 190907
Use the .Metadata
property to retrieve a IPropertyBase
. That will tell you what has actually changed.
Upvotes: 2