Search code examples
audit.net

Audit.Net Entity Framework Provider: Save the DB operation before the audit log


I've been trying out the Audit.NET Entity Framework provider without using inheritance, outlined in https://github.com/thepirat000/Audit.NET/tree/master/src/Audit.EntityFramework#without-inheritance

Is there a way to save the DB operations first, and then create the AuditEvent? I noticed that if you had DB constraints configured, the Audit event still fires, while DbContext.SaveChangesAsync throws an Exception on the main thread.

This snippet performs the DB operation, but doesn't fire the Audit event:

public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
    {
        try
        {   
            int saveResult = await base.SaveChangesAsync(cancellationToken);
            return await _helper.SaveChangesAsync(_auditContext, () => Task.FromResult(saveResult));
        }
        catch (Exception)
        {
            throw;
        }
    }

But if I replace the two lines to just

return await _helper.SaveChangesAsync(_auditContext, () => base.SaveChangesAsync(cancellationToken));

it works fine, but the Audit happens before the DB operation. What am I missing here?


Solution

  • Under normal circumstances and by default, the audit saving happens after the DbContext.SaveChanges returns. You can check the code here.

    The scope creation is done before the DB operation, but the audit saving is not triggered until the context has finished the operation.

    You should not use the first approach, you should only call the _helper.SaveChanges on your override.