Entity framework 使用实体框架CommandTree拦截器添加额外的数据库命令

Entity framework 使用实体框架CommandTree拦截器添加额外的数据库命令,entity-framework,entity-framework-6.1,Entity Framework,Entity Framework 6.1,我试图在实体框架中实现一个可审计的数据存储。我的意图是保存每个记录在任何给定时间点的状态的历史记录。这要求我将所有delete语句转换为updates,将所有update语句转换为update+insert 我根据视频了解了拦截器的基本设置,但我已经到了不确定如何继续的地步。我有查询、删除和插入的有效案例,但更新是个棘手的问题 以下是该方法的基本结构: public void TreeCreated(DbCommandTreeInterceptionContext interceptionCon

我试图在实体框架中实现一个可审计的数据存储。我的意图是保存每个记录在任何给定时间点的状态的历史记录。这要求我将所有delete语句转换为updates,将所有update语句转换为update+insert

我根据视频了解了拦截器的基本设置,但我已经到了不确定如何继续的地步。我有查询、删除和插入的有效案例,但更新是个棘手的问题

以下是该方法的基本结构:

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
方法中做的是不可能的


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

在这种情况下,您可以覆盖应用程序数据库上下文中的
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();
    }
public override int SaveChanges()
{
List dbEntityEntries=ChangeTracker.Entries()
其中(e=>e.Entity为Person&&e.State==EntityState.Modified)
托利斯先生()
foreach(dbEntityEntries中的变量dbEntityEntrie)
{
var person=(person)addedCourse.Entity;
var log=新日志()
{
Name=person.Name;
}
日志。添加(日志);
}
返回base.SaveChanges();
}
您可以使用继承和泛型重构此代码