The below C# code executes in 3 seconds. I listed the SQL Profiler output as well. If I change the statement to not use Dynamic SQL it executes in milliseconds. I can’t find any good resources to give a solution to this problem. But I was able to find an article that explaine that in Dynamic SQL since the parser doesn’t know the value of the parameters, it cannot optimize the query plan.
public string GetIncorporation(Parcel parcel)
{
var result = (from c in _context.Districts
where c.PARCEL_ID == parcel.PARCEL_ID && c.DB_YEAR == parcel.DB_YEAR && c.DISTRICT_CD.CompareTo("9000") < 0
select c).ToList();
exec sp_executesql N'SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
MAX([Filter1].[A1]) AS [A1]
FROM ( SELECT
SUBSTRING([Extent1].[DISTRICT_CD], 0 + 1, 2) + N''00'' AS [A1]
FROM [STAGE].[DISTRICT] AS [Extent1]
WHERE ([Extent1].[PARCEL_ID] = @p__linq__0) AND ([Extent1].[DB_YEAR] = @p__linq__1) AND ([Extent1].[DISTRICT_CD] < N''9000'')
) AS [Filter1]
) AS [GroupBy1]',N'@p__linq__0 nvarchar(4000),@p__linq__1 int',@p__linq__0=N'0001-02-0003',@p__linq__1=2012
I’m trying to build a service layer. I don’t want to have a mixed batch of Stored Procedures and Linq Queries
Did you paste that query in SSMS, run the execution plan, and see if it suggestions any missing indexes?
Also, if you don’t need all the columns from the table, limit them by using a select:
or