Entity Framework cached query plan performance degrades with different parameters

跟風遠走 提交于 2019-11-29 04:47:24

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.

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)'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!