我有一个基于实体框架的数据库,其中包含一些实体/模型/表。例如,对于Documents
模型,我想在一个名为DocumentChanges
模型/表的单独表中跟踪该表中每个记录的所有更改。
能否请您指导我如何启用/告诉EF在单独的表中跟踪/审计对表的所有更改,不仅仅是一个日期-时间戳,而是将每次更改的完整记录保存在一个单独的表中。
库Audit.EntityFramework可以帮助您完成所需操作。
您需要实现自己的DataProvider
来存储您希望格式化的数据。
例如:
void StartUp()
{
//Setup to use your own provider to store the data
Audit.Core.Configuration.Setup()
.UseCustomProvider(new YourDataProvider());
//Setup to audit EF operations only for the table Documents
//(Your DbContext must inherit from AuditDbContext)
Audit.EntityFramework.Configuration.Setup()
.ForAnyContext(x => x.IncludeEntityObjects())
.UseOptIn()
.Include<Documents>();
}
class YourDataProvider : AuditDataProvider
{
public override object InsertEvent(AuditEvent auditEvent)
{
//Get some enviroment info:
var userName = auditEvent.Environment.UserName
//Get the complete log for the EF operation:
var efEvent = auditEvent.GetEntityFrameworkEvent();
foreach(var entry in efEvent.Entries)
{
// each entry is a modified entity (updated, deleted or inserted)
if (entry.Action == "Update")
{
//You can access the column values
var value = entry.ColumnValues["ID"];
//...or the columns changes
var changes = entry.Changes.Select(ch => ch.ColumnName + ": " +
ch.OriginalValue + " -> " + ch.NewValue);
}
//... insert into DocumentChanges table
}
return id;
}
}