MVC 5 - 在数据库中记录插入和更新

时间:2014-07-15 08:42:52

标签: asp.net-mvc entity-framework audit-logging

我已经寻找了很多不同的方法来实现这个目标。但是我还没有找到一个很好的简单的例子来说明如何做到这一点,而没有很多关于性能记录和调试的3方派对。

我正在寻找一种方法来轻松地将所有更改记录到我的数据库中,以及添加新行时。我希望有一个自己的表来存储控制器被调用的操作/或者只是数据库表足以跟踪它。以及更新或添加的字段。 我正在想象一个像这样的表:

ID - ACTION/TABLE/METHOD - ID -  TYPE - DETAILS - CREATED BY - TIMESTAMP

 x - TableName/ActionResult/JsonResult/ - ID of the new or updated item - updated or new - details on what have changed or created - user.identity - timestamp

所以我可以在每个特定视图中查看日志表,我可以看到该项目的历史记录以及更改的字段等。

我查看了这里的底层建议:How to implement a MVC 4 change log?因为我的SQL数据库不支持SQL Service Broker,我真的不想从SQL中添加触发器开始。

我正在使用MVC 5.2和EF 6.0,所以我查看了Database.Log属性,但我真的需要一些指导如何设置一个好的方法来实现我想要的。

1 个答案:

答案 0 :(得分:4)

我找到了一个我正在修改我的需求的解决方案。

以下是代码:

中覆盖SaveChanges类
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>

并添加theese方法:

public async Task SaveChangesAsync(string userId)
        {

            // Get all Added/Deleted/Modified entities (not Unmodified or Detached)
            foreach (var ent in this.ChangeTracker.Entries().Where(p => p.State == EntityState.Added || p.State == EntityState.Deleted || p.State == EntityState.Modified))
            {
                // For each changed record, get the audit record entries and add them
                foreach (Log x in GetAuditRecordsForChange(ent, userId))
                {
                    this.Log.Add(x);
                }
            }

            // Call the original SaveChanges(), which will save both the changes made and the audit records
            await base.SaveChangesAsync();
        }

        private List<Log> GetAuditRecordsForChange(DbEntityEntry dbEntry, string userId)
        {
            List<Log> result = new List<Log>();

            DateTime changeTime = DateTime.Now;

            // Get the Table() attribute, if one exists
            TableAttribute tableAttr = dbEntry.Entity.GetType().GetCustomAttributes(typeof(TableAttribute), false).SingleOrDefault() as TableAttribute;

            // Get table name (if it has a Table attribute, use that, otherwise get the pluralized name)
            string tableName = tableAttr != null ? tableAttr.Name : dbEntry.Entity.GetType().Name;

            // Get primary key value (If you have more than one key column, this will need to be adjusted)
            string keyName = dbEntry.Entity.GetType().GetProperties().Single(p => p.GetCustomAttributes(typeof(KeyAttribute), false).Count() > 0).Name;

            if (dbEntry.State == EntityState.Added)
            {
                // For Inserts, just add the whole record
                // If the entity implements IDescribableEntity, use the description from Describe(), otherwise use ToString()
                result.Add(new Log()
                {
                    LogID = Guid.NewGuid(),
                    EventType = "A", // Added
                    TableName = tableName,
                    RecordID = dbEntry.CurrentValues.GetValue<object>(keyName).ToString(),  // Again, adjust this if you have a multi-column key
                    ColumnName = "*ALL",    // Or make it nullable, whatever you want
                    NewValue = (dbEntry.CurrentValues.ToObject() is IDescribableEntity) ? (dbEntry.CurrentValues.ToObject() as IDescribableEntity).Describe() : dbEntry.CurrentValues.ToObject().ToString(),
                    Created_by = userId,
                    Created_date = changeTime
                }
                    );
            }
            else if (dbEntry.State == EntityState.Deleted)
            {
                // Same with deletes, do the whole record, and use either the description from Describe() or ToString()
                result.Add(new Log()
                {
                    LogID = Guid.NewGuid(),
                    EventType = "D", // Deleted
                    TableName = tableName,
                    RecordID = dbEntry.OriginalValues.GetValue<object>(keyName).ToString(),
                    ColumnName = "*ALL",
                    NewValue = (dbEntry.OriginalValues.ToObject() is IDescribableEntity) ? (dbEntry.OriginalValues.ToObject() as IDescribableEntity).Describe() : dbEntry.OriginalValues.ToObject().ToString(),
                    Created_by = userId,
                    Created_date = changeTime
                }
                    );
            }
            else if (dbEntry.State == EntityState.Modified)
            {
                foreach (string propertyName in dbEntry.OriginalValues.PropertyNames)
                {
                    // For updates, we only want to capture the columns that actually changed
                    if (!object.Equals(dbEntry.OriginalValues.GetValue<object>(propertyName), dbEntry.CurrentValues.GetValue<object>(propertyName)))
                    {
                        result.Add(new Log()
                        {
                            LogID = Guid.NewGuid(),
                            EventType = "M",    // Modified
                            TableName = tableName,
                            RecordID = dbEntry.OriginalValues.GetValue<object>(keyName).ToString(),
                            ColumnName = propertyName,
                            OriginalValue = dbEntry.OriginalValues.GetValue<object>(propertyName) == null ? null : dbEntry.OriginalValues.GetValue<object>(propertyName).ToString(),
                            NewValue = dbEntry.CurrentValues.GetValue<object>(propertyName) == null ? null : dbEntry.CurrentValues.GetValue<object>(propertyName).ToString(),
                            Created_by = userId,
                            Created_date = changeTime
                        }
                            );
                    }
                }
            }
            // Otherwise, don't do anything, we don't care about Unchanged or Detached entities

            return result;
        }

        public DbSet<Log> Log { get; set; }

这是Log类

[Table("N_Log")]
public class Log
{
    [Key]
    public Guid LogID { get; set; }

    [Required]
    public string EventType { get; set; }

    [Required]
    public string TableName { get; set; }

    public string ActionID { get; set; }

    [Required]
    public string RecordID { get; set; }

    [Required]
    public string ColumnName { get; set; }

    public string OriginalValue { get; set; }

    public string NewValue { get; set; }

    [Required]
    public string Created_by { get; set; }

    [Required]
    public DateTime Created_date { get; set; }
}