インターネット上のいくつかのフォーラムを調べても解決できなかった一般的な問題があります。
ASP.NET WebAPI を使用するレストラン評価アプリケーションがあります。このアプリには、Restaurant テーブルと Comments テーブルの 2 つのテーブルがあります。各レストランには複数のコメントがあり、各コメントには評価値があります。私は 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."