如何在 Entity Framework 中启用单独审核 Table

How to enable Seperate Audits Table in Entity Framework

我有一个基于 Entity Framework 的数据库,其中有几个 entities/models/table。例如Documents 模型,我想在名为 DocumentChanges Model/Table.

的单独 table 中跟踪每个记录的所有更改

能否请您指导我 如何 enable/tell EF 到 track/audit 所有更改 到 table 单独的 table?,不仅仅是日期时间戳,而是在单独的 table.

中保存每次更改的完整记录

图书馆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;
    }
}