来自多个表的 Linq Count 项目

Linq Count item from multiple tables

我有下面的 2 个表格,我想按 CategoryCode

计算类别的图书数量
ID bookName CategoryCode
1 ULYSSES B1
2 Dye Yielding Plants B3
3 Sapiens B2
4 LOLITA B1
CategoryCode CategoryName
B1 Novel Book
B2 knowledge Book
B3 General Book

我希望结果是:

CategoryCode CategoryName ItemCount
B1 Novel Book 2
B2 Knowledge Book 1
B3 General book 1

这是我的代码

var CountItem = (from p in context.Product
                        join c in context.Category on p.CategoryCode equals c.CategoryCode
                    group p by p.CategoryCode 
                    into g 
                    select new {
                        Key = g.Key, Count = g.Select(x => x.CategoryCode).Distinct().Count() 
                    }).ToList();

看来我走错了方向。请帮助我

我不明白你为什么要使用 distinct,但如果你只想计算类别中的每本书,这个请求应该有效

from p in books
group p by p.CategoryCode
into g
join c in categories on g.Key equals c.CategoryCode
select new
{
   CategoryCode = g.Key,
   CategoryName = c.Name,
   ItemCount = g.Count()
};