我在将sql转换为linq语法时遇到困难。

我有2个表(Category和CategoryListing),它们通过CategoryID相互引用。我需要获取“类别表”中所有CategoryID的列表以及“类别列表”表中所有相应匹配项的“类别ID计数”。如果CategoryListing中没有CategoryID,则应该仍返回CategoryID-频率为0。

以下sql查询演示了预期的结果:

SELECT c.CategoryID, COALESCE(cl.frequency, 0) as frequency
FROM Category c
LEFT JOIN (
    SELECT cl.CategoryID, COUNT(cl.CategoryID) as frequency
    FROM CategoryListing cl
    GROUP BY cl.CategoryID
) as cl
ON c.CategoryID = cl.CategoryID
WHERE c.GuideID = 1

最佳答案

未经测试,但这应该可以解决问题:

var q = from c in ctx.Category
        join clg in
            (
                from cl in ctx.CategoryListing
                group cl by cl.CategoryID into g
                select new { CategoryID = g.Key, Frequency = g.Count()}
            ) on c.CategoryID equals clg.CategoryID into cclg
        from v in cclg.DefaultIfEmpty()
        where c.GuideID==1
        select new { c.CategoryID, Frequency = v.Frequency ?? 0 };

关于.net - Linq在包含Count的子查询上具有左联接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/560453/

10-17 01:02