私は2つのテーブルA
とB
. は1 対多 (のコレクションを含む) としてA
関連付けられています。B
A
B
次の SQL を生成するように Entity Framework を作成するにはどうすればよいですか (どの 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]
よろしくお願いします!