我正在尝试用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(); %>
有人对我如何加快速度有什么建议吗?我怀疑问题是我试图用一种愚蠢的方式来做——通常是这样!
您可以尝试执行计数的Sum
而不是SelectMany
:
tg.Enrolments.Sum(e => e.Student.Progressions
.Count(p => p.TTMChecked == false &&
p.TTMInterview == true &&
p.AcademicYear == year)
);
应该使用以下语法编写:
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)
。