Linq with Left Join on SubQuery包含Count

时间:2009-02-18 10:04:03

标签: .net linq count subquery left-join

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

我有2个表(Category和CategoryListing),它们使用CategoryID互相引用。我需要在CategoryListing表中获取Category Category中所有CategoryID的列表和CategoryID的所有相应匹配的Count。如果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

2 个答案:

答案 0 :(得分:13)

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

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 };

答案 1 :(得分:0)

我继续将整个查询移动到数据库上的存储过程。这首先避免使用LINQ来解决问题。