首页 > 解决方案 > 如何从 AuditLog 表中获取主键 (Audit.Core.Configuration.AddCustomAction(ActionType.OnEventSaved)

问题描述

我正在使用此代码块将审核信息保存到详细信息表中。在此保存期间,我需要从刚刚保存的 AuditLog 表记录中获取 PK,以便添加 Detail 记录。

Audit.Core.Configuration.AddCustomAction(ActionType.OnEventSaved, scope =>
{
   auditService.ConfigureAuditDetail(scope);
});

因为我只有可用的范围,所以我无法找到 AuditLog 实体,除非通过上下文查找。这是安全的还是在我得到正确的 PK 之前可以保存另一条记录。

ctx.AuditLog.OrderByDescending(x => x.Id).FirstOrDefault().Id;

有没有办法更好地做到这一点?

    public void ConfigureAuditDetail(AuditScope scope)  
    {
        var efEvent = (scope.Event as AuditEventEntityFramework)?.EntityFrameworkEvent;
        
        List<EventEntryChange> currentChanges = new List<EventEntryChange>();
        var ctx = efEvent.GetDbContext() as DbContext;

       var auditLogId = ctx.AuditLog.OrderByDescending(x => x.Id).FirstOrDefault().Id;
     }

标签: audit.net

解决方案


如果你像这样映射你的审计表,那么AuditLog有一个集合AuditLogDetails

public class AuditLog
{ 
    public int Id { get; set; }
    public ICollection<AuditLogDetail> Details { get; set; }
    public string Table { get; set; }
    public string Action { get; set; }
}

public class AuditLogDetail
{
    public int Id { get; set; }
    public int AuditLogId { get; set; }
    public string Column { get; set; }
    public string Value { get; set; }
}

然后,您可以像这样为 Audit EF 指定映射和操作:

Audit.Core.Configuration.Setup()
    .UseEntityFramework(ef => ef
        .UseDbContext<MyContext>()
        .AuditTypeMapper(t => typeof(AuditLog))
        .AuditEntityAction<AuditLog>((auditEvent, entry, auditLog) =>
        {
            auditLog.Table = entry.Table;
            auditLog.Action = entry.Action;
            auditLog.Details = entry.ColumnValues.Select(c => new AuditLogDetail()
            {
                Column = c.Key,
                Value = c.Value.ToString()
            }).ToList();
        })
        .IgnoreMatchedProperties());

所以审计实体保存在同一个事务中。


推荐阅读