修改实体框架的表达式树,使其尽可能接近T-SQL翻译\执行

Ami*_*ich 4 c# expression entity-framework iqueryable odata

我已经能够IQueryable使用ExpressionVisitor和其他自定义修改表达式Expressions

我的问题是使用实体框架的第三方框架(例如,OData),它们在内部方法内部以及在某些地方使查询难以修改后修改查询的地方。

在过程的最后,有一个IQueryable表示表达式树的。实体框架知道如何将表达式树转换为T-SQL并执行它。

我正在尝试将其修改Expression\IQueryable为尽可能接近执行。

我这样做的最好方法是什么?

Tit*_*mir 6

您可以使用实体框架拦截。这使您可以在执行之前拦截所有查询(包括导航属性查询)

实体框架允许我们在查询生成的不同方面指定不同类型的拦截器。每个拦截器都可以修改要执行的查询。拦截器类型为:

  1. IDbCommandInterceptor执行查询时将调用此拦截器的方法。该查询将已经在SQL中进行了转换,并将设置参数。

  2. IDbCommandTreeInterceptor创建命令树时将调用此拦截器的方法。命令树是命令的AST表示。生成了两个命令树,一个以概念模型(DataSpace.CSpace)表示,该命令树将更接近LINQ查询,而另一个以存储模型(DataSpace.SSpace)表示。

  3. IDbConfigurationInterceptorDbConfiguration加载时将调用此拦截器的方法。

  4. IDbConnectionInterceptor 建立连接和发生事务时将调用此拦截器的方法。

  5. IDbTransactionInterceptor 提交或回滚事务时,将调用此拦截器的方法。

IDbCommandTreeInterceptor提供了一种获取并更改命令的好方法。AST非常易于理解,并且Entity Framework已经提供了用于基于现有AST创建新命令AST的基础结构(命令AST是不可变的结构,因此我们不能仅更改现有的AST)。

用法示例:

class CustomExpressionVisitor : DefaultExpressionVisitor
{
    // Override method to mutate the query 
}
class TestInterceptor : IDbCommandTreeInterceptor
{
    public void TreeCreated(DbCommandTreeInterceptionContext interceptionContext)
    {
        if (interceptionContext.Result.DataSpace == DataSpace.CSpace)
        {
            // We only process query command trees 
            // (there can be others such as insert, update or delete
            var queryCommand = interceptionContext.Result as DbQueryCommandTree;
            if (queryCommand != null)
            {
                // A bit of logging to see the original tree
                Console.WriteLine(queryCommand.DataSpace);
                Console.WriteLine(queryCommand);

                // We call the accept method on the command expression with our new visitor. 
                // This method will return our new command expression with the changes the 
                // visitor has made to it
                var newQuery = queryCommand.Query.Accept(new CustomExpressionVisitor());
                // We create a new command with our new command expression and tell 
                // EF to use it as the result of the query
                interceptionContext.Result = new DbQueryCommandTree
                (
                     queryCommand.MetadataWorkspace,
                     queryCommand.DataSpace,
                     newQuery
                 );
                // A bit of logging to see the new command tree
                Console.WriteLine(interceptionContext.Result);
            }

        }

    }
}

// In code before using any EF context.
// Interceptors are registered globally.
DbInterception.Add(new TestInterceptor());
Run Code Online (Sandbox Code Playgroud)

注意:查询计划已缓存,因此第一次遇到查询并缓存查询时将不会调用拦截(您指定的结果将被缓存,而不是原始结果)。因此,对于不依赖于上下文的更改(例如:用户,请求,语言),可以安全地使用它。