Entity Framework cached query plan performance degrades with different parameters

后端 未结 2 474
时光说笑
时光说笑 2020-12-17 02:30

I have the following problem.

Background

I\'m trying to implement an autocomplete selector with MVC3, EF4 and jquery over a table wit 4.5 million records.<

相关标签:
2条回答
  • 2020-12-17 03:08

    There's a way to remove a single plan from SQL Server's cache. It's explained in detail here: http://sqlblog.com/blogs/kalen_delaney/archive/2007/09/29/geek-city-clearing-a-single-plan-from-cache.aspx

    Also, you can create a Stored Procedure, and map it with Entity Framework instead of using LINQ2Entities, and in this way make spcific changes to the SQL syntax, and make sure it's always the same.

    0 讨论(0)
  • 2020-12-17 03:31

    As you identified, SQL Server compiles the plan to be optimized for one parameter value with large result set. When the result set is narrowed, the query doesn't perform well.

    This scenario requires the use of "option (recompile)" hint in the query, so the query will be recompiled for each value it receives.

    It's not so easy to do this with entity framework. You will need to create a DbCommandInterceptor to include option (recompile) in the query. Another option is to create a plan guide in SQL Server to add the "option (recompile)" to the query.

    You will find information about the DbCommandInterceptor here - Adding a query hint when calling Table-Valued Function

    About the plan guide, you will need something similar to this:

    EXEC sp_create_plan_guide   
    'planguidename',   
    N'SELECT TOP (50) 
    [Project1].[C1] AS [C1], 
    [Project1].[C2] AS [C2], 
    [Project1].[afpCUIT] AS [afpCUIT]
    FROM ( SELECT 
        [Extent1].[afpCUIT] AS [afpCUIT], 
        [Extent1].[afpNombre] AS [afpNombre], 
        1 AS [C1], 
        RTRIM([Extent1].[afpNombre]) AS [C2]
        FROM [dbo].[CONSTA] AS [Extent1]
        WHERE [Extent1].[afpCUIT] LIKE @p__linq__0 ESCAPE N''~''
    )  AS [Project1]
    ORDER BY [Project1].[afpNombre] ASC',
    'SQL',   
    NULL,   
    N'@p__linq__0 nvarchar(4000)',
    N'OPTION (recompile)'
    
    0 讨论(0)
提交回复
热议问题