我试图将以下SQL查询转换为LINQ,
SELECT
C.CategoryId
, CategoryName
,COUNT(DISTINCT I.ItemId)
FROM
Categories C
LEFT JOIN Items I
ON I.CategoryId = C.CategoryId AND I.SubCategoryId = 1
GROUP BY C.CategoryId, C.CategoryName
即使项目数为0,也需要所有类别。
答案 0 :(得分:2)
使用群组联接,它应该看起来像这样......
var result = Categories
.GroupJoin(
Items.Where(i => i.SubCategoryId == 1),
c => c.CategoryId,
i => i.CategoryId,
(c, i) => new { c.CategoryId, c.CategoryName, i.Count() })