我有两个表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
我尝试了下一个:
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]
预先感谢!