Search code examples
entity-framework-coreasp.net-core-webapiaudit.net

Can I configure Audit.NET to create audit records in two tables on for one audit event?


I am currently implementing Audit.NET into an ASP.NET Core Web API project that is using EF Core. I am using the Entity Framework Data Provider and currently have it configured to map all entities to a single audit log (AuditLog) table with the code below.

Audit.Core.Configuration.Setup()
.UseEntityFramework(_ => _
    .AuditTypeMapper(t => typeof(AuditLog))  
    .AuditEntityAction<AuditLog>((ev, entry, audit) =>
    {
        audit.Date = DateTime.UtcNow;
        audit.AuditData = JsonConvert.SerializeObject(entry);
        audit.UserIdentifier = userId;
    })
.IgnoreMatchedProperties(true));

This is working great, however, I would like to write audit entries to the BlogApprovals table if the entity type is Blog - in addition to the entry getting added to AuditLog. So for a Blog entity I would like an audit record in both BlogApprovals and AuditLog. Is this possible?


Solution

  • Not really, since the EntityFrameworkDataProvider is designed to map each entity to only one audit entity.

    But you could trigger the extra insert, after the operation is complete, by using an OnSaving Custom Action, like this:

    Audit.Core.Configuration.AddOnSavingAction(scope =>
    {
        // OnSaving event fires after context SaveChanges 
        var efEvent = (scope.Event as AuditEventEntityFramework)?.EntityFrameworkEvent;
        if (efEvent != null && efEvent.Success)
        {
            foreach (var e in efEvent.Entries)
            {
                if (e.Table == "Blogs" && e.Action == "Insert")
                {
                    // there was an insert on blogs table, insert the blogapproval
                    var ctx = efEvent.GetDbContext() as MyContext;
                    ctx.BlogApproval.Add(new BlogApproval() { Note = "note..." });
                    (ctx as IAuditBypass).SaveChangesBypassAudit();
                }
            }
        }
    });