0

我的数据库的每个表最后都有 2 列,允许记录(执行操作的用户和操作的日期)。编辑:我使用代码优先迁移。
所以我希望自动填充这两个日志记录列:

  1. 每次我在表中插入一个新条目时(使用 DbContext.[Model].Add(entry))

  2. 或者每次我执行 DbContext.SaveChanges() 操作时


我考虑过重写 DbContext.SaveChanges() 方法,但没有成功……

我也尝试过覆盖 DbSet Add() 方法,在那里执行日志填充操作。为此,我创建了一个继承自 DbSet 的 CustomDbSet 类:

public class CustomDbSet<TEntity> : DbSet<TEntity> where TEntity : class
    {
        public TEntity Add(TEntity entity)
        {
            //Do logging action here
            return base.Add(entity);
        }
    }

但这也没有成功。
编辑:这个 CustomDbSet 发生的事情是任何 DbContext.[Model] 返回 null,现在(而不是填充数据库表的内容)

我已经有了将执行日志记录操作的扩展方法,但我没有知道把它放在哪里,所以日志记录将成为一个“自动”操作..

public static void EntityLogCreate<T>(this T model, string userName) where T : LogColumns
{
    model.Create_User = userName;
    model.Create_Date = DateTime.Now;
}

有什么想法可以实现吗?

4

1 回答 1

0

这是一个如何做到这一点的例子。

public class AppContext : DbContext
{
    public DbSet<Item> Items { get; set; }
    public override int SaveChanges()
    {
        int actionById = 1; // Need a way to get the user who does the action.
        DateTime actionDate = DateTime.Now;
        var entries = ChangeTracker.Entries<IAuditLog>();
        foreach (var entry in entries)
        {
            if (entry.State != EntityState.Added && entry.State != EntityState.Modified) continue;
            // Only added and modified entries.
            entry.Entity.ActionById = actionById;
            entry.Entity.ActionDate = actionDate;
        }
        return base.SaveChanges();
    }
}
public interface IAuditLog
{
    int? ActionById { get; set; }
    DateTime? ActionDate { get; set; }
}
public class Item : IAuditLog
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? ActionById { get; set; }
    public DateTime? ActionDate { get; set; }
}
于 2014-07-31T08:49:58.303 回答