audit.net - 如何从 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;
}
解决方案
如果你像这样映射你的审计表,那么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());
所以审计实体保存在同一个事务中。
推荐阅读
- android - 是否可以在 google play 上使用新密钥上传 android 应用程序
- java - 无法为自定义编辑文本应用样式
- android - 是否有可能将android应用程序启动时间减少到几乎为零?(如 Instagram 和 WhatsApp 新更新)
- python - 在 Python 的其他模块中使用主模块中的实例
- c# - 将 linq sum 查询迁移到 .net core 3.1
- android - 是否可以使用 kotlin 将数据从 recyclerview 适配器共享到 bottomsheetdialogfragment?
- java - Java 复合模式:为什么我不能自己添加一个组?
- python - 从 Queryset Django 中填写缺失的数据
- reactjs - 如何定义组件类型?
- r - quantmod 两次向图表添加指标