【问题标题】:Add extra database command with Entity Framework CommandTree interceptor使用 Entity Framework CommandTree 拦截器添加额外的数据库命令
【发布时间】:2015-01-11 01:35:31
【问题描述】:

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

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

这是该方法的基本结构:

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

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

有没有一种方法可以使用拦截器完成我想做的事情而不使用数据库触发器?

【问题讨论】:

    标签: entity-framework entity-framework-6.1


    【解决方案1】:

    在这种情况下,您可以覆盖 AppicationDbContext 中的 savechanges()。您可以使用内置属性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();
        }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-07
      • 1970-01-01
      • 2016-07-08
      • 2017-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多