EntityFramework Core: Get changes occured in entity and related data

.net-core asp.net-core c# entity-framework-core

Question

I want to get changes occured in an entity and related datas attached to it.

I know how to get the property names that have changed in one entity:

 dbContext.Entry(entity).Properties.Where(x => x.IsModified).Select(x => x.Metadata.Name).ToList();

How to do the same for related data in navigation properties ?

1
3
10/30/2018 12:46:17 PM

Accepted Answer

Based on this article (Entity Change Tracking using DbContext in Entity Framework 6), you should override SaveChanges() method to track entity changes and its related entities.

public override int SaveChanges()
{
    return base.SaveChanges();
} 

Actually, You should change the above code to the following sample:

public override int SaveChanges()
{
    var modifiedEntities = ChangeTracker.Entries()
        .Where(p => p.State == EntityState.Modified).ToList();
    var now = DateTime.UtcNow;

    foreach (var change in modifiedEntities)
    {
        var entityName = change.Entity.GetType().Name;
        var primaryKey = GetPrimaryKeyValue(change);

        foreach(var prop in change.OriginalValues.PropertyNames)
        {
            var originalValue = change.OriginalValues[prop].ToString();
            var currentValue = change.CurrentValues[prop].ToString();
            if (originalValue != currentValue) //Only create a log if the value changes
            {
                //Create the Change Log
            }
        }
    }
    return base.SaveChanges();
}
6
10/30/2018 5:35:39 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