我有三个表,实体,期间和结果。实体和期间之间存在1:1映射,期间和结果之间存在1:多。
这是linq查询:
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 })
这是生成的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')
SELECT Count(*)来自哪里,如何摆脱它?我不需要为每个“期间”计算“结果”,它会使查询减慢一个数量级。
答案 0 :(得分:1)
考虑使用Context.LoadOptions并指定Period to LoadWith(p => p.Results)来急切加载带有结果的句点,而不需要投射到匿名类型。