Getting OldValue and NewValue of an Audit entities property every time even though the entity has been modified

344 Views Asked by At

I am using the Entity Framework Plus Audit package: docs here

I have implemented the following code in my dbContext.

Overload of the SaveChanges() method:

public override int SaveChanges()
{
    var audit = new Z.EntityFramework.Plus.Audit
    {
        Configuration =
        {
            IgnorePropertyUnchanged = false
        }
    };
    
    audit.PreSaveChanges(this);
    var rowsAffected = base.SaveChanges();
    audit.PostSaveChanges();
    
    if (audit.Configuration.AutoSavePreAction == null)
    {
        return rowsAffected;
    }
    
    audit.Configuration.AutoSavePreAction(this, audit);

    base.SaveChanges();

    return rowsAffected;
}

This is my config in the constructor:

public TimedWorkflowDbContext(DbContextOptions options) : base(options)
{
    AuditManager.DefaultConfiguration.IgnoreEntityUnchanged = false;
    AuditManager.DefaultConfiguration.Exclude<TimedWorkflowActivity>();
    
    AuditManager.DefaultConfiguration.AutoSavePreAction = (context, audit) =>
    {
        audit.Entries.ForEach(x=> x.CreatedDate = DateTime.UtcNow);
        (context as TimedWorkflowDbContext)?.AuditEntries.AddRange(audit.Entries);
    };

}

Now what my problem is: the entities properties whether updated or not, the oldValue and the newValue are the same.

enter image description here

I know I have IgnorePropertyUnchanged = false, but if I remove this then only the Id(key) gets audited and written in the database as an audit property.

What could be the problem?

1

There are 1 best solutions below

0
Jonathan Magnan On

As answered to this question here: https://github.com/zzzprojects/EntityFramework-Plus/issues/759

One common problem is that the entity gets attached instead of being retrieved from the database. When an entity gets attached, the state manager is not aware of the old value. So the OldValue get the NewValue value because this is the only value know.

Something similar to this issue