加速linq查询

时间:2013-02-07 16:34:56

标签: asp.net-mvc linq linq-to-sql

我正在尝试使用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(); %>

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

2 个答案:

答案 0 :(得分:1)

您可以尝试执行Sum计数而不是SelectMany

tg.Enrolments.Sum(e => e.Student.Progressions
                                .Count(p => p.TTMChecked == false && 
                                            p.TTMInterview == true && 
                                            p.AcademicYear == year)
                  );

答案 1 :(得分: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的类型为BIT而不是INT,请考虑使用.Equals(true)