2013-04-07 229 views
0
過濾子元素

我有以下實體:LEFT JOIN在LINQ

student (
    studentID int, 
    name string 
) 


subject (
    .... 
    studentID int, 
    passed bit, 
    date date 
) 

我希望有一個表來顯示所有的學生和學科計數的名單,學生可在2012年

然後我創建下面的linq,但失敗。

(from x in db.student 
    join y in db.subject on x.studentID equals y.studentID into z 
from s in z.DefaultIfEmpty() where s.date.Year.Equals(2012) 
    select new { 
     x.studentID, 
     x.name, 
     SubjectPassCount = y.passed.Equals(true).Count 
}).Distinct() 

有人請幫忙嗎?感謝

回答

0

試試這個

var results = 
    (from x in db.student 
    join y in db.subject.Where(s => s.date.Year == 2012 && s.passed) 
     on x.studentID equals y.studentID into z 
    select new 
    { 
      x.studentID, 
      x.name, 
      SubjectPassCount = z.Count() 
    }) 
    .Distinct() 

或可能

var results = 
    (from x in db.student 
    join y in db.subject 
     on new { x.studentID, 2012, true } equals new { y.studentID, y.date.Year, y.passed } into z 
    select new 
    { 
      x.studentID, 
      x.name, 
      SubjectPassCount = z.Count() 
    }) 
    .Distinct() 
+0

「計數(謂詞)」方法不支持LINQ to Entities。 – MarcinJuraszek 2013-04-07 14:20:06

+0

@MarcinJuraszek我認爲這是固定在EF的最新版本。無論如何,我更新了我的答案。 – 2013-04-07 14:23:55

0

我會更where條件一點點。您還需要聲明group by來統計每個學生的科目數量。

(from x in db.student 
join y in db.subject.Where(s => s.date.Year == 2012 && s.passed == true) on x.studentID equals y.studentID into z 
from s in z.DefaultIfEmpty() 
group new {x, s} by new { x.studentID, x.name } into g 
select new { 
    g.Key.studentID, 
    g.Key.name, 
    SubjectPassCount = g.Where(gi => gr.s != null).Count() 
}).Distinct() 
0

如果有一個導航屬性student.subjects那樣簡單

from x in db.student 
    select new { 
     x.studentID, 
     x.name, 
     SubjectPassCount = x.subjects.Where(s => s.passed && s.Year == 2012) 
            .Count() 
    }) 

(或x.subjects.Count(s => s.passed && s.Year == 2012)其在EF 5至少支持)它可以。