我有两个表A
和B
。A
与B
是一对多关系(A
包含B
的集合)。
我如何使实体框架生成下一个SQL(我应该写什么linq查询):
SELECT A.UserId, COUNT(B.ID) FROM A
LEFT JOIN B ON A.ID = B.A_ID
WHERE B.Score <= 6
GROUP BY A.UserId
I have try next:
from a in db.A
join b in db.B
on a.ID equals b.A_ID
where b.Score <= 6
group a by a.UserId into grouping
select new
{
UserId = (Guid) grouping.Key,
RawValue = grouping.Sum(x => x.Bs.Count())
};
它返回我需要的东西,但是EF将它转换成可怕的查询(这就是为什么这个查询的性能非常差)。
生成的SQL:
SELECT
1 AS [C1],
[Project3].[UserId] AS [UserId],
CAST( [Project3].[C1] AS float) AS [C3]
FROM ( SELECT
[Project2].[UserId] AS [UserId],
(SELECT
SUM([Filter2].[A1]) AS [A1]
FROM ( SELECT
(SELECT
COUNT(1) AS [A1]
FROM [dbo].[B] AS [Extent5]
WHERE [Extent3].[ID] = [Extent5].[A_ID]) AS [A1]
FROM [dbo].[A] AS [Extent3]
INNER JOIN [dbo].[B] AS [Extent4] ON [Extent3].[ID] = [Extent4].[A_ID]
WHERE ([Extent4].[Score] <= 6)
) AS [Filter2]) AS [C1]
FROM ( SELECT
[Distinct1].[UserId] AS [UserId]
FROM ( SELECT DISTINCT
[Extent1].[UserId] AS [UserId]
FROM [dbo].[A] AS [Extent1]
INNER JOIN [dbo].[B] AS [Extent2] ON [Extent1].[ID] = [Extent2].[A_ID]
WHERE ([Extent2].[Score] <= 6)
) AS [Distinct1]
) AS [Project2]
) AS [Project3]
谢谢先!
当我用
改变你的ef时from a in db.A.DefaultIfEmpty()
join b in db.B
on a.ID equals b.A_ID
where b.Score <= 6
group a by a.UserId into grouping
select new
{
UserId = (string) grouping.Key,
RawValue = grouping.Count()
};
使用
生成的SQL更改SELECT
1 AS [C1],
[GroupBy1].[K1] AS [UserId],
[GroupBy1].[A1] AS [C2]
FROM ( SELECT
[Extent1].[UserId] AS [K1],
COUNT(1) AS [A1]
FROM ( SELECT 1 AS X ) AS [SingleRowTable1]
LEFT OUTER JOIN [dbo].[A] AS [Extent1] ON 1 = 1
INNER JOIN [dbo].[B] AS [Extent2] ON [Extent1].[ID] = [Extent2].[A_ID]
WHERE [Extent2].[Score] <= 6
GROUP BY [Extent1].[UserId]
) AS [GroupBy1]
我认为这是非常好的优化结果。