3

我已经寻找了很多不同的方法来实现这一点。但是我还没有找到一个好的和简单的例子来说明如何在没有大量 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

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

我在这里查看了底部建议:如何实现 MVC 4 更改日志?因为我的 SQL 数据库不支持 SQL Service Broker,而且我真的不想从在 SQL 中添加触发器开始。

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

4

1 回答 1

4

I found a solution i am currently modifying to my needs.

Here is the code:

Overriding SaveChanges Class in

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>

and adding theese methods:

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; }

And here is the Log class

[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; }
}
于 2014-07-16T07:33:21.823 回答