I am using EntityFramework to select data from my mssql database. My query looks something like this:
int param = 123456;
using (var context = new DatabaseContext())
{
var query = context.Table.AsQueryable();
var result = query.Where(o => o.Id == param).ToList();
}
This query takes about 10 seconds.
using (var context = new DatabaseContext())
{
var query = context.Table.AsQueryable();
var result = query.Where(o => o.Id == 123456).ToList();
}
This query takes less than 1 second.
I just found out that EntityFramework generates two different queries.
Query 1:
SELECT TOP (20)
[Project1].[Id] AS [Id],
[Project1].[Name] AS [Name],
FROM ( SELECT [Project1].[Id] AS [Id], [Project1].[Name] AS [Name], row_number() OVER (ORDER BY [Project1].[Id] DESC) AS [row_number]
FROM ( SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name]
FROM [dbo].[Table] AS [Extent1]
WHERE [Extent1].[Id] = @p__linq__0
) AS [Project1]
) AS [Project1]
WHERE [Project1].[row_number] > 0
ORDER BY [Project1].[Id] DESC
-- p__linq__0: '2932323' (Type = Int32, IsNullable = false)
Query 2:
SELECT TOP (20)
[Filter1].[Id] AS [Id],
[Filter1].[Name] AS [Name]
FROM ( SELECT [Extent1].[Id] AS [Id], [Extent1].[Name] AS [Name], row_number() OVER (ORDER BY [Extent1].[Id] DESC) AS [row_number]
FROM [dbo].[Table] AS [Extent1]
WHERE 2932323 = [Extent1].[Id]
) AS [Filter1]
WHERE [Filter1].[row_number] > 0
ORDER BY [Filter1].[Id] DESC
Is there a way to speed up the first one or another way to do it?
imho, seen the sql queries, this is not (only) an EF related performance problem, but an SQL server performance problem.
You should considers the following:
EXEC sp_updatestats
to update the statistics and help the db server to produce better execution plans.btw: how long takes query 1 in SSMS ?
I found the solution.
I dropped all execution plans using sp_recompile and now all is working fine.
Thx for your help.
P.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With