我在SQL中有一个简单的查询,我想将其转换为Linq to Entities。
基本上,我想要数据库中的所有可用课程,但我想要特定用户的每个课程的最后测试结果,如果他们已经完成了课程。他们可能已多次参加课程,但我只想要每次测试的最后一次测试结果。这有可能用一个Linq声明吗?
这是SQL:
select c.courseid, c.Name, ca.result
from Course c
left join CourseAttempt ca
on c.CourseId = ca.CourseId
and ca.CourseAttemptId in
(
select max(courseattemptid)
from courseattempt
where userid=1234
group by courseid
)
这是我到目前为止所做的:
var stuff = (from c in context.Course
join ca in context.CourseAttempt.Where(a => a.userid == _userid)
on c.CourseId equals ca.Course.CourseId into jca
select new
{
courseId = c.CourseId,
name = c.Name,
result = jca.Select(a => a.result)
}).ToList();
问题是结果是所有结果的数组。我怎么才能得到最后的结果?
答案 0 :(得分:0)
此解决方案有效:
var stuff = (from c in context.Course
join ca in context.CourseAttempt.Where(a => a.user.userid == _userid)
on c.CourseId equals ca.Course.CourseId into jca
select new
{
courseId = c.CourseId,
name = c.Name,
result = jca.OrderByDescending(a => a.CourseAttemptId).Take(1).Select(a => a.result).Cast<int>().DefaultIfEmpty(-1).FirstOrDefault()
}).ToList();