【问题标题】:How to enable Seperate Audits Table in Entity Framework如何在实体框架中启用单独的审计表
【发布时间】:2016-02-24 10:48:59
【问题描述】:

我有一个基于实体框架的数据库,其中包含一些实体/模型/表。例如Documents Model,我想在名为 DocumentChanges Model/Table 的单独表中跟踪对该表中每条记录的所有更改。

您能否指导我如何启用/告诉 EF 跟踪/审核所有更改到表在单独的表中?,而不仅仅是日期时间戳,但将每次更改的完整记录保存在单独的表中。

【问题讨论】:

    标签: entity-framework tracking audit


    【解决方案1】:

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

    【讨论】:

    • 如果它还可以根据 IP 和主机等选项捕获更多信息,那就太好了
    • 它确实捕获了主机,查看基本输出here。但可以添加 IP 地址。
    • 2016年sql server/express的create DB结构报错,请检查更新
    • @aggie 请在 git 上打开 issue 以跟进。 SQL Server Express 也不支持JSON dataAFAIK
    猜你喜欢
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    • 2017-04-03
    • 2013-10-31
    • 1970-01-01
    • 2016-12-30
    相关资源
    最近更新 更多