0

我有以下实体:

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

有人可以帮忙吗?谢谢

4

3 回答 3

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()
于 2013-04-07T14:17:13.470 回答
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()
于 2013-04-07T14:17:39.550 回答
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 中受支持)。

于 2013-04-07T19:18:14.580 回答