Rewriting a LINQ Expression query to enable caching SQL Execution Plan

后端 未结 2 1106
攒了一身酷
攒了一身酷 2020-12-31 18:14

While reading an article on Entity Framework performance, I came across this piece of information:

Secondly, the problem [SQL Server won’t reu

2条回答
  •  耶瑟儿~
    2020-12-31 18:43

    After a lot of trial and error, we found you can still force Entity Framework to recognise convertedId as a parameter by slightly changing how we pass it in:

    ....
    
    var convObj = new
    {
        id = convertedId
    };
    var rightExp = Expression.Convert(Expression.Property(Expression.Constant(convObj), "id"), convertedId.GetType());
    
    var whereExpression = Expression.Lambda>
        (
        Expression.Equal(
            Expression.Property(
                itemParameter,
                prop.Name
                ),
            rightExp
            ),
        new[] { itemParameter }
        );
    
    return Get().Where(whereExpression);
    

    Which causes the generated SQL to use the same parameter (and code) for any given id:

    WHERE [Extent1].[Id] = @p__linq__0 
    

    The query in question that we were dealing with takes a long time to generate the execution plan, so we saw a significant decrease in execution time for accessing new IDs (from 3~4 seconds down to ~300 milliseconds)

提交回复
热议问题