【发布时间】:2018-10-28 04:51:04
【问题描述】:
我在我的应用程序中使用 EF 和 DotNet Core 2.1。该应用程序处理多个相关表和 FK 互连表中的数据。
我只需要对一张表的审计日志数据进行更改。但是,我的问题是,我需要审核日志的表有相当多的 FK,对于其中的每一个,我都想记录 FK 本身和相关表中的字段。
让我试着说明一下我的意思 - 假设这是我的模型:
public class Blog {
public int Id { get; set; }
public string Name { get; set; }
public string Url { get; set; }
[InverseProperty ("Blog")]
public ICollection<Post> Posts { get; set; }
public Blog() {
Posts = new Collection<Post> ();
}
}
...
[AuditInclude]
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
[Required]
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
如前所述,我希望审计日志只更改一个实体 - 假设它是 Post - 这是一个审计类:
public class Audit_Post : IAudit {
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public string Blog { get; set; } // <- I need populating this from Blog.Name
[StringLength (64)]
public string AuditUsername { get; set; }
public DateTime AuditDt { get; set; }
public string AuditAction { get; set; }
public Audit_Manufacturer () { }
}
这就是我在startup.cs -> ConfigureService() 中设置审计日志的方式:
...
Audit.Core.Configuration.Setup ()
.UseEntityFramework (ef => ef
.AuditTypeExplicitMapper (m => m
.Map<Post, Audit_Post> ((d, al) => {
al.Blog = d.Blog?.Name; // !! This doesn't work
})
.AuditEntityAction<IAudit> ((evt, entry, auditEntity) => {
Object val;
var gotVal = evt.CustomFields.TryGetValue ("AuditUsername", out val);
string username = null;
if (gotVal && val is string)
username = val as string;
else
username = "<anonymous>";
auditEntity.AuditDt = DateTime.UtcNow;
auditEntity.AuditUsername = username;
auditEntity.AuditAction = entry.Action;
})
)
);
问题:是否有可能从依赖表(一对多)关系中获取和审核日志数据?
除了提到的问题之外,我还遇到了一个离题的问题,那就是 - 如果我忘记使用迁移来更新数据库以初始化 Audit_Posts 表并且我正在对 Posts 表进行操作,即使审计日志无法写入(UnitOfWork 保存异常),数据也会存储到后面。 AuditDbContext 是否有一个标志可以使其在与原始查询相同的事务中运行?
【问题讨论】:
标签: ef-core-2.1 audit.net