I am trying to calculate the average rating for a product category and the total number of ratings received. In the example below, I would like to get the average rating/count for the shirts category.
Here is the schema:
Product Table
| ProdId | CatId | Name |
|---|---|---|
| 1 | Shirts | Cotton Tee |
| 2 | Pants | Sweatpants |
| 3 | Pants | Jeans |
Rating Table
| RatingId | ProdId | Rating |
|---|---|---|
| 1 | 1 | 5 |
| 2 | 1 | 4 |
| 3 | 3 | 5 |
| 4 | 2 | NULL |
Here is the code I have tried that throws an error:
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()
});
Try following :