【问题标题】:Can I configure Audit.NET to create audit records in two tables on for one audit event?我可以将 Audit.NET 配置为在两个表中为一个审计事件创建审计记录吗?
【发布时间】:2020-05-09 05:23:58
【问题描述】:

我目前正在使用 EF Core 的 ASP.NET Core Web API 项目中实现 Audit.NET。我正在使用Entity Framework Data Provider,目前已将其配置为使用以下代码将所有实体映射到单个审核日志 (AuditLog) 表。

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 表 - 除了添加到 AuditLog 的条目。因此,对于Blog 实体,我想要both BlogApprovalsAuditLog 中的审计记录。这可能吗?

【问题讨论】:

    标签: entity-framework-core asp.net-core-webapi audit.net


    【解决方案1】:

    并非如此,因为EntityFrameworkDataProvider 旨在将每个实体映射到仅一个审计实体。

    但是你可以在操作完成后触发额外的插入,通过使用OnSavingCustom 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();
                }
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-11
      • 2020-05-30
      • 2021-05-20
      • 2013-06-28
      • 2018-11-02
      • 2014-12-07
      • 1970-01-01
      相关资源
      最近更新 更多