2011-03-23 159 views
1

我在SQL中有一個簡單的查詢,我想將它轉換爲實體。Tyring將SQL轉換爲LINQ到實體

基本上,我想要數據庫中的所有可用課程,但是我希望每個課程對於特定用戶的最後一次測試結果(如果他們參加了課程)。他們可能多次參加過課程,但我只想要每次測試的最後一次測試結果。這可能與一個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

此解決方案:

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();