我有三个表格:产品,类别和等级。我正在尝试获得产品和产品类别的平均评分。这是我所做的,但是它给了我相同的评级,该评级仅适用于产品而不适用于其类别。
public class Ratings
{
public int RatingId { get; set; }
public int Rating { get; set; }
public int ProductId { get; set; }
}
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
}
public class Products
{
public int ProductId { get; set; }
public string Name { get; set; }
public int CategoryId { get; set; }
}
这些是我的查询
var tmparray = db.Rating.Include(n => n.Products)
.Where(x => x.Products.CategoryId == CategoryId).Take(1)
.GroupBy(p => p.ProductsId, o => o.Rating)
.Select(p => new
{
ProductsId = p.Key,
AverageCategory = p.Average()
});
var tmparray2 = db.Ocjene
.GroupBy(p => p.ProductsId, o => o.Rating)
.Select(p => new
{
ProductsId = p.Key,
Average = p.Average()
});
答案 0 :(得分:1)
每个Rating
都知道其Product
,每个Product
都知道其Category
,因此我们可以按类别输入并返回到Rating。然后将结果按类别分组。
var ratingsByCategory = from c in categories
join p in products on c.CategoryId equals p.CategoryId
join r in ratings on p.ProductId equals r.ProductId
group new
{
categoryId = c.CategoryId,
rating = r.Rating
} by c.CategoryId into g
select new
{
categoryId = g.Key,
rating = g.Average(r=>r.rating)
};
在此处共享运行示例:.Net Fiddle