0

私は2つのテーブルAB. は1 対多 (のコレクションを含む) としてA関連付けられています。BAB

次の 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]

よろしくお願いします!

4

1 に答える 1

0

私があなたの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]

これは非常に優れた最適化結果だと思います。

于 2013-01-02T14:13:14.690 に答える