Reputation: 504
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?
Upvotes: 1
Views: 1095
Reputation: 13114
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();
}
}
}
});
Upvotes: 1