Linq到Sql左连接并获取平均值

Linq到Sql左连接并获取平均值,linq,Linq,假设我有一个Linq查询: var query = from course in _unitOfWork.Course.GetAll() join candidate in _unitOfWork.CandidateCourses.GetAll() on course.Id equals candidate.Course_id join cr in _unitOfWork.CourseReviews.GetAll() on course.Id equals cr.Cou

假设我有一个Linq查询:

var query = from course in _unitOfWork.Course.GetAll() 
            join candidate in _unitOfWork.CandidateCourses.GetAll() on course.Id equals candidate.Course_id join cr in _unitOfWork.CourseReviews.GetAll() on course.Id equals cr.Course_id into g from rt in g.DefaultIfEmpty() 
            where candidate.UserId == CandidateId 
            select new CourseFields { Id = course.Id, 
                                      Course_name = course.Course_name, 
                                      Course_description = course.Course_description,
                                      Rating = g.Average(x => x.Rating), 
                                      TotalSections = sections.Count(), };
在这里,我在计算评分平均值时遇到了一个例外,因为表中并没有该课程的数据


有人能帮我找出哪里做错了吗?

Average
需要在序列中列出一个元素

如果不存在任何元素,可以添加
DefaultIfEmpty
来设置默认评级

...
Rating = g.DefaultIfEmpty(0).Average(x => x.Rating),
...
如果您的评级为
Nullable
类型(如
Nullable>

然后它不会抛出异常,而是重新运行
null

,您也可以尝试一下这个。在进行平均值计算之前检查空值


那么,如果没有记录,您希望评级是什么?您使用的是实体框架吗?并不是说它会改变这个错误,但是有一种更优雅的方式用lambda符号来写这个。
Rating = (g!=null && g.Count()>0)?g.Average(x => x.Rating):0,