我可以配置 Audit.NET 为一个审计事件在两个表中创建审计记录吗?
Can I configure Audit.NET to create audit records in two tables on for one audit event?
我目前正在实施 Audit.NET into an ASP.NET Core Web API project that is using EF Core. I am using the Entity Framework Data Provider,目前已将其配置为使用以下代码将所有实体映射到单个审计日志 (AuditLog
) table。
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));
这很好用,但是,如果实体类型是 Blog
,我想将审计条目写入 BlogApprovals
table - 除了条目被添加到AuditLog
。因此,对于 Blog
实体,我想要 BlogApprovals
和 AuditLog
中的审计记录。这可能吗?
并非如此,因为 EntityFrameworkDataProvider
旨在将每个实体仅映射到一个审计实体。
但是您可以在操作完成后触发额外的插入,通过使用 OnSaving
Custom Action,如下所示:
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();
}
}
}
});
我目前正在实施 Audit.NET into an ASP.NET Core Web API project that is using EF Core. I am using the Entity Framework Data Provider,目前已将其配置为使用以下代码将所有实体映射到单个审计日志 (AuditLog
) table。
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));
这很好用,但是,如果实体类型是 Blog
,我想将审计条目写入 BlogApprovals
table - 除了条目被添加到AuditLog
。因此,对于 Blog
实体,我想要 BlogApprovals
和 AuditLog
中的审计记录。这可能吗?
并非如此,因为 EntityFrameworkDataProvider
旨在将每个实体仅映射到一个审计实体。
但是您可以在操作完成后触发额外的插入,通过使用 OnSaving
Custom Action,如下所示:
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();
}
}
}
});