EF Core with Angular - query fast in SQL Profiler, slow in practice

127 Views Asked by At

I have a not so big db - 6 tables, up to 400 records each, 4 joins. My problem is that queries are slow when in practice. It used to take 30 secs, it randomly dropped to 2 sec, and back again, etc. when reading almost the whole db, then it seemed to stay at 2sec. Some were saying my PC has not enough RAM. So I introduced paging with 10 record a page, and it's still more than 2 sec on the frontend, although SQL Profiler says it's done in 10-20ms. Without includes with 10 records stays 2sec.

LINQ:

        var events = await eventRepository
            .GetAllWith()
            .Skip(page * 10)
            .Take(10)
            .Include(e => e.Sport)
            .Include(e => e.League)
            .Include(e => e.Markets)
                .ThenInclude(m => m.Results)
            .ToListAsync();

Here's the query that runs:

exec sp_executesql N'SELECT [t].[Id], [t].[AwayTeam], [t].[Date], [t].[HomeTeam], [t].[LeagueId], [t].[Outcome], [t].[SportId], [s].[Id], [s].[Name], [l].[Id], [l].[Name], [l].[SportId], [t0].[Id], [t0].[EventId], [t0].[id0], [t0].[MarketId], [t0].[name], [t0].[odds], [t0].[sourceName]
FROM (
    SELECT [e].[Id], [e].[AwayTeam], [e].[Date], [e].[HomeTeam], [e].[LeagueId], [e].[Outcome], [e].[SportId]
    FROM [Event] AS [e]
    ORDER BY (SELECT 1)
    OFFSET @__p_0 ROWS FETCH NEXT @__p_1 ROWS ONLY
) AS [t]
INNER JOIN [Sport] AS [s] ON [t].[SportId] = [s].[Id]
INNER JOIN [League] AS [l] ON [t].[LeagueId] = [l].[Id]
LEFT JOIN (
    SELECT [m].[Id], [m].[EventId], [r].[id] AS [id0], [r].[MarketId], [r].[name], [r].[odds], [r].[sourceName]
    FROM [Market] AS [m]
    LEFT JOIN [ResultEntity] AS [r] ON [m].[Id] = [r].[MarketId]
) AS [t0] ON [t].[Id] = [t0].[EventId]
ORDER BY [t].[Id], [s].[Id], [l].[Id], [t0].[Id], [t0].[id0]',N'@__p_0 int,@__p_1 int',@__p_0=0,@__p_1=10

I tried to change nvarchars to varchars, eliminate nullable equality checks, but it didn't solve my problem. How could I solve it?

0

There are 0 best solutions below