我有一个常见的问题,我无法通过查看互联网上的几个论坛来解决。
我有一个使用 ASP.NET WebAPI 的餐厅评级应用程序。该应用程序有两个表餐厅和评论表。每个餐厅可能有多个评论,每个评论都有一个评分值。我试图在 WebAPI 中组合一个方法,通过查看评论表从餐厅表中提取详细信息以及每个餐厅的平均评分值。到目前为止,我的尝试是在下面的代码中,它不起作用。我尝试过使用聚合函数、平均函数、嵌套查询、连接等,但仍然无法提取平均值。如果有人可以提供帮助,我将不胜感激?
public IQueryable<RestaurantView> GetRestaurants(string All)
{
var query = from x in db.Restaurants
select new RestaurantView
{
RestaurantID = x.RestaurantID,
RestaurantName = x.RestaurantName,
RestaurantDecription = x.RestaurantDecription
RestaurantRatingAverage = (from a in db.Restaurants
join b in db.Comments on a.RestaurantID equals b.CommentsRestaurantID into z
from c in z
group c by c.CommentsRestaurantID into g
select new
{
RatingAverage = Convert.ToDouble(g.Average(a => a.CommentsRating))
};)
};
return query;
}
更新:使用乔纳森的技术(见下文)
public IQueryable<RestaurantView> GetRestaurants(string All)
{
var query = from x in db.Restaurants
select new RestaurantView
{
RestaurantID = x.RestaurantID,
RestaurantName = x.RestaurantName,
RestaurantDecription = x.RestaurantDecription,
RestaurantRatingAverage = (from a in db.Comments
where a.CommentsRestaurantID.Equals(x.RestaurantID)select a.CommentsRating).Average()
};
return query;
}
但我现在得到以下异常
An error has occurred.","ExceptionMessage":"The cast to value type 'Double' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type."