1

我正在尝试使用 linq 复制以下 SQL 查询。在 SQL Server 上运行只需几分之一秒:

select g.reference, count(*)
from isis.dbo.[group] as g inner join
     isis.dbo.enrolment as e on g.groupid = e.groupid inner join
     isis.dbo.student as s on e.studentid = s.studentid inner join
     isis.dbo.progression as p on s.studentid = p.studentid
where p.academicyear = '12/13' and g.istutorgroup = 1 
group by reference

在我的 MVC 应用程序中,我将“TutorGroups”列表传递给视图。对于视图中的每个导师组,我需要显示有关他们的各种信息,其中一项是他们进行的“进步”采访的数量。

我尝试了几种方法,但它们都需要 30 秒以上才能在我的 MVC 应用程序中运行:

<%TTMrequired = tg.Enrolments
                  .SelectMany(e => e.Student.Progressions
                                    .Where(p => p.TTMChecked == false && 
                                                p.TTMInterview == true && 
                                                p.AcademicYear == year))
                  .Count(); %>

<%TTMrequired = tg.Enrolments
                  .Where(e => e.Student.Progressions
                               .Any(p => p.TTMChecked == false && 
                                         p.TTMInterview == true && 
                                         p.AcademicYear == year))
                  .Count(); %>

有人对我如何加快速度有任何建议吗?我怀疑问题是我试图以一种愚蠢的方式去做——通常是这样!

4

2 回答 2

1

您可以尝试做 a Sumof counts 而不是 a SelectMany

tg.Enrolments.Sum(e => e.Student.Progressions
                                .Count(p => p.TTMChecked == false && 
                                            p.TTMInterview == true && 
                                            p.AcademicYear == year)
                  );
于 2013-02-07T16:39:06.173 回答
0

应该使用以下语法编写:

var TTMRequired = (from g in tg.Groups 
                   join e in tg.Enrolment on g.groupid equals e.groupid
                   join s in tg.Students on e.studentid equals s.studentid
                   join p in tg.Progressions on s.studentid = p.studentid
                   where p.academicyear.Equals("12/13") && g.istutorgroup.Equals(1)
                   group g by g.reference into grp
                   select new { 
                      grpRef = grp.Key,
                      grpCount = grp.Count()
                   });

注意:如果g.istutorgroup是 typeBIT而不是INT,请考虑使用.Equals(true).

于 2013-02-07T16:45:19.170 回答