Christopher
Christopher

Reputation: 10627

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.

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

Answers (1)

Daniel A. White
Daniel A. White

Reputation: 190907

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

Upvotes: 2

Related Questions