How can I optimize this Linq query to remove an unnecessary SELECT (*) counter

I have three tables: Entity, Period, and Result. There is a 1: 1 mapping between Entity and Period and a 1: Many between period and result.

This is the linq request:

int id = 100;
DateTime start = DateTime.Now;

from p in db.Periods
where p.Entity.ObjectId == id && p.Start == start
select new { Period = p, Results = p.Results })

These are the relevant parts of the generated SQL:

SELECT [t0].[EntityId], [t2].[PeriodId], [t2].[Value], (
    SELECT COUNT(*)
    FROM [dbo].[Result] AS [t3]
    WHERE [t3].[PeriodId] = [t0].[Id]
    ) AS [value2]

FROM [dbo].[Period] AS [t0]
INNER JOIN [dbo].[Entity] AS [t1] ON [t1].[Id] = [t0].[EntityId]
LEFT OUTER JOIN [dbo].[Result] AS [t2] ON [t2].[PeriodId] = [t0].[Id]
WHERE ([t1].[ObjectId] = 100) AND ([t0].[Start] = '2010-02-01 00:00:00')

Where do SELECT Count (*) come from and how can I get rid of it? I do not need to calculate the “Results” for each “Period”, and it slows down the query by an order of magnitude.

+3
source share
1 answer

Consider using Context.LoadOptions and directions for Period to LoadWith (p => p.Results) to animate the loading of the period with the results without having to project into an anonymous type.

+1
source

All Articles