You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Audit.Net时,如何获取实体对应的审计实体以查询审计记录?

问题解答

Audit.Net 目前并没有提供公开的API来直接获取你配置的应用实体与审计实体的映射关系,不过你可以通过以下两种方式解决这个问题:

1. 自行维护映射字典(推荐)

在配置Audit映射的同时,同步维护一份自己的类型映射字典,后续查询时直接从字典中获取对应关系即可。这种方式不受Audit.Net内部实现变更的影响,稳定性更高。

示例代码:

// 全局维护实体-审计实体映射字典
public static class AuditMappingHelper
{
    public static readonly Dictionary<Type, Type> EntityToAuditTypeMap = new();
}

// Audit配置时同步更新字典
config.AuditTypeExplicitMapper(m =>
{
    m.Map<Client, ClientAudit>();
    AuditMappingHelper.EntityToAuditTypeMap.Add(typeof(Client), typeof(ClientAudit));
    
    m.AuditEntityAction<IAuditEntity>(SetAuditEntity);
});

// 查询审计记录时使用
if (AuditMappingHelper.EntityToAuditTypeMap.TryGetValue(typeof(Client), out var auditEntityType))
{
    // 使用auditEntityType在审计DbContext中查询对应记录
    // 示例:var auditRecords = await auditContext.Set(auditEntityType).Where(...).ToListAsync();
}

2. 通过反射访问Audit.Net内部映射(不推荐)

Audit.Net的显式映射关系实际存储在ExplicitAuditMapper类的内部字段中,你可以通过反射读取这个集合,但这种方式依赖框架内部实现,若后续Audit.Net更新调整内部结构,代码可能会失效。

示例代码:

// 获取全局配置的显式映射器实例
var explicitMapper = Audit.Core.Configuration.AuditTypeMapper as ExplicitAuditMapper;
if (explicitMapper != null)
{
    // 反射获取内部的_typeMap字段
    var typeMapField = typeof(ExplicitAuditMapper).GetField("_typeMap", 
        System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
    if (typeMapField != null)
    {
        var typeMap = typeMapField.GetValue(explicitMapper) as Dictionary<Type, Type>;
        if (typeMap != null && typeMap.TryGetValue(typeof(Client), out var auditType))
        {
            // 使用auditType进行查询操作
        }
    }
}

内容的提问来源于stack exchange,提问作者Adam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 04:12:44