我可以在实体框架中访问 IDbCommandInterceptor 中的实体吗

Pau*_*ies 5 .net c# sql entity-framework interceptor

实现 IDbCommandInterceptor 时,我可以访问为命令/查询创建的 SQL 命令。是否还可以访问在实现的方法中持久/检索的实际实体对象?

这是一些幻想代码来演示我想做的事情:

public class WidgetInterceptor : IDbCommandInterceptor
{
    public void NonQueryExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
    {
        var widget = interceptionContext.Entity as Widget;

        if(widget != null)
        {
            //Perform tasks on widget before it is saved...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

jle*_*lew 1

在查询的情况下,没有一个实体。执行的 SQL 命令可以返回任意数量的行,这可能会导致具体化实体或某种投影。您可以访问所涉及的 DbContext 或 ObjectContext,并通过其 ChangeTracker 查看其中实体的状态,但据我所知,没有直接的方法将您正在执行的特定命令与任何特定实体关联起来。根据您的上下文,ChangeTracker 中实体的数量、类型和状态可能足以完成您想要的操作。