我有一个基于 Entity Framework 的数据库,其中包含一些实体/模型/表。例如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;
}
}
关于entity-framework - 如何在 Entity Framework 中启用单独的审计表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33852261/