我是Audit.net的新手。我在项目中成功配置了它。
但是现在,我需要扩展它以保存额外的信息,例如requesterID和在视图页面上写的注释。
我的案子: 实体已映射到Entity_AT
Entity {
[Key]
int ID
string label
}
Entity_AT {
[Key]
int ATID
int ID
string label
int ATFlag
datetime ATCreationDate
string RequesterID
string ATComment
}
public void Add(TEntity obj, string RequesterId)
{
_dbSet.Add(obj);
_context.SaveChanges();
}
[AuditDbContext(Mode = AuditOptionMode.OptOut, IncludeEntityObjects = false, AuditEventType = "{database}_{context}")]
public class MyDBContext : AuditIdentityDbContext<ApplicationUser>
{
}
Audit.Core.Configuration.DataProvider = new EntityFrameworkDataProvider()
{
AuditTypeMapper = t => t == typeof(Entity) ? typeof(Entity_AT) : null,
AuditEntityAction = (evt, entry, auditEntity) =>
{
var a = (dynamic)auditEntity;
a.ATCreationDate = DateTime.UtcNow;
a.ATFlag = (entry.Action == "Insert") ? 1 : (entry.Action == "Update") ? 2 : (entry.Action == "Delete") ? 3 : 0;
return true; // return false to ignore the audit
}
};
我尝试过:
_context.AddAuditCustomField("RequesterId", requesterId);
_context.AddAuditCustomField("ATComment", "pippo");
_dbSet.Add(obj);
_context.SaveChanges();
但没有结果
答案 0 :(得分:0)
您已将"RequesterId"
自定义字段添加到AuditEvent
,但没有将其映射到AuditEntity
属性。
您应该对实体操作执行以下操作:
Audit.Core.Configuration.DataProvider = new EntityFrameworkDataProvider()
{
AuditTypeMapper = t => t == typeof(Entity) ? typeof(Entity_AT) : null,
AuditEntityAction = (evt, entry, auditEntity) =>
{
var a = (dynamic)auditEntity;
a.ATCreationDate = ...;
a.ATFlag = ...;
a.RequesterID = evt.CustomFields["RequesterId"] as string;
a.ATComment = evt.CustomFields["ATComment"] as string;
return true;
}
};
请注意,您也可以使用Fluent API使用更简洁的语法来配置数据提供程序:
Audit.Core.Configuration.Setup()
.UseEntityFramework(_ => _
.AuditTypeExplicitMapper(map => map
.Map<Entity, Entity_AT>((evt, entry, auditEntity) =>
{
auditEntity.ATCreationDate = ...;
auditEntity.ATFlag = ...;
auditEntity.RequesterID = evt.CustomFields["RequesterId"] as string;
auditEntity.ATComment = evt.CustomFields["ATComment"] as string;
})));