Linq to SQL 计算平均值并使用连接计数

问题描述 投票:0回答:0

我正在尝试计算产品类别的平均评分和收到的评分总数。在下面的示例中,我想获得衬衫类别的平均评分/计数。

这是架构:

产品表

产品编号 CatId 姓名
1 衬衫 棉T恤
2 裤子 运动裤
3 裤子 牛仔裤

评级表

RatingId 产品编号 评分
1 1 5
2 1 4
3 3 5
4 2

这是我尝试过的代码,它会引发错误:

var AggregateRating = db.Ratings.Join(db.Products, r => r.ProdId, p  => p.ProdId, (r, p) => new { r, p })
    .Where(x => x.p.CatId == CatId && x.r.Rating != null).GroupBy(x => x.p.CatID).Select(x => new
    {
        rating = x.Average(y => y.r.Rating),
        count = x.Count()
    });
c# linq linq-to-sql
© www.soinside.com 2019 - 2024. All rights reserved.