Hold Old and New value in SaveChange as DbEntityEntry.Entity to Audit

那年仲夏 提交于 2019-12-07 02:32:27
Aria

First I should thanks to thepirat000 who made Audit.Net lib, this is very nice lib to Audit with many option as he mentioned in GitHub

but about my problem, this is my first time to override SaveChange() and I didn't know DbEntityEntry object as well, but the solution seems so funny, just need to convert CurrentValues and OriginalValues to Object(), in modify case I am getting the old value by dbEntry.OriginalValues.ToObject() and change it with dbEntry.CurrentValues.ToObject() in Audit.Net scope, that is all.

  Logging.Log(LoggingMode.Prompt, "Saving Audid Entry{0}....", dbEntry.ToString()); 
        TableAttribute tableAttr = dbEntry.Entity.GetType().GetCustomAttributes(typeof(TableAttribute), true).SingleOrDefault() as TableAttribute;
        string tableName = tableAttr != null ? tableAttr.Name : dbEntry.Entity.GetType().Name;
        Logging.Log(LoggingMode.Prompt, "TableName Retrived {0}...", tableName);
        switch (dbEntry.State)
        {
            case System.Data.Entity.EntityState.Added:
                int result = base.SaveChanges();
                object addedObj = dbEntry.Entity;
                using (var audit = Audit.Core.AuditScope.Create("Add " + tableName, () =>addedObj ))
                {
                    audit.SetCustomField("UserGUID", userGUID);
                    addedObj = null;
                } 
                return result;
            case System.Data.Entity.EntityState.Deleted:
                object deletedObj = dbEntry.Entity;
                using (var audit = Audit.Core.AuditScope.Create("Delete " + tableName, () => deletedObj))
                {
                    audit.SetCustomField("UserGUID", userGUID);
                    deletedObj = null;
                }  
                break;
            case System.Data.Entity.EntityState.Modified: 
                object en = dbEntry.OriginalValues.ToObject();
                using (var audit = Audit.Core.AuditScope.Create("Edit " + tableName, () => en))
                {
                    audit.SetCustomField("UserGUID", userGUID);
                    en = dbEntry.CurrentValues.ToObject();
                }
                break;
            default:
                break;
        }
        return base.SaveChanges();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!