3

我正在尝试在实体框架中实现可审计的数据存储。我的目的是在任何给定时间点保留每条记录状态的历史记录。这要求我将所有删除语句转换为更新,并将所有更新语句转换为更新 + 插入。

我按照TechEd 2014 EF6 软删除会话视频进行拦截器的基本设置,但我已经到了不知道如何继续的地步。我有查询、删除和插入的有效案例,但更新是一个棘手的案例。

这是该方法的基本结构:

public void TreeCreated(DbCommandTreeInterceptionContext interceptionContext)
{
    if (interceptionContext.OriginalResult.DataSpace == DataSpace.SSpace)
    {
        //other query interceptors

        var updateCommand = interceptionContext.OriginalResult as DbUpdateCommandTree;
        if (updateCommand != null)
        {
            //I modify the command to soft delete the current record
            //(This is pseudo code to replace to verbose EF exp builder code)
            var newClause = GetNewSoftDeleteClause(updateCommand);
            interceptionContext.Result = GetUpdateCommandTree(updateCommand, newClause);

            //Here is where I want to insert a new command into the tree
            //and copy over the data to a new record
        }
    }
}

据我所知,可以修改方法中的当前ResultTreeCreated但我找不到将新命令插入上下文的方法。由于拦截器似乎只处理单行操作,我开始认为我想做的事情在TreeCreated方法中是不可能的。

有没有办法在不使用数据库触发器的情况下使用拦截器完成我想做的事情?

4

1 回答 1

0

在这种情况下,您可以覆盖savechanges()AppicationDbContext 中的 。您可以使用内置属性ChangeTracker找出要更新的对象,然后附加需要插入的新对象。

 public override int SaveChanges()
    {
        List<DbEntityEntry> dbEntityEntries= ChangeTracker.Entries()
                .Where(e => e.Entity is Person && e.State == EntityState.Modified)
                .ToList()

        foreach(var dbEntityEntrie in dbEntityEntries)
        {
             var person = (Person)addedCourse.Entity;
             var log= new Log()
               {
                   Name=person.Name;
               }
             Logs.Add(log);
        }

        return base.SaveChanges();
    }

您可以使用继承和泛型重构此代码。

于 2015-01-10T17:35:31.257 回答