How can I detect changes to properties in a specific entity in Entity Framework Core 2.x?

c# entity-framework entity-framework-core

Question

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();
}
1
2
1/18/2019 9:52:28 PM

Accepted Answer

Use the .Metadata property to retrieve a IPropertyBase. That will tell you what has actually changed.

1
1/18/2019 9:09:54 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow