我有以下(不正确的)LINQ 函数(更新):
public IQueryable<ClassUsageReport> GetClassUsage()
{
//Class Code, Title, Usage, FiscalYear
var queryable = (from agencyplan in _agencyPlansList
join classSchedule2012 in _classSchedule2012List
on agencyplan.Id equals classSchedule2012.AgencyPlanId
join classes in _classesList
on classSchedule2012.Class.Id equals classes.Id
orderby agencyplan.PlanYear.FiscalYear descending, classes.ClassCode.Count() descending
group agencyplan by new
{
agencyplan.PlanYear.FiscalYear,
classes.ClassCode,
classes.Title
} into gcs
select new ClassUsageReport
{
ClassCode = gcs.Key.ClassCode,
Title = gcs.Key.Title,
Usage = gcs.Key.ClassCode.Count(),
FiscalYear = gcs.Key.FiscalYear
}
);
return queryable.AsQueryable();
}
我在使用 Group By 和 Order By 子句时遇到问题。也可以使用 COUNT()。
我已经编写了正确的 SQL 语句,它根据需要(和预期)产生结果:
select py.fiscalyear, c.classcode, c.title, count(c.classcode) as usage from classschedule2012 cs
inner join classes c on cs.class_id = c.id
inner join agencyplans ap on cs.agencyplanid = ap.Id
inner join planyears py on ap.planyear_id = py.id
group by py.fiscalyear, c.classcode, c.title
order by py.fiscalyear desc, usage desc
我的 LINQ 语句中的分组和排序有什么问题?我希望它像我的 SQL 一样包含“用法”。如何获得计数以正确反映真实计数?由于目前的查询,它只在每一行中返回“9”。这与我的 SQL 不匹配,因为真正的结果应该是 "55, 44, 14, 13" 等等......
编辑:2013 年 11 月 14 日
这是最终结果:
public IQueryable<ClassUsageReport> GetClassUsage()
{
//Class Code, Title, Usage, FiscalYear
var queryable = (from agencyplan in _agencyPlansList
join classSchedule2012 in _classSchedule2012List
on agencyplan.Id equals classSchedule2012.AgencyPlanId
join classes in _classesList
on classSchedule2012.Class.Id equals classes.Id
where classes.Active = true
orderby agencyplan.PlanYear.FiscalYear descending
group agencyplan by new
{
agencyplan.PlanYear.FiscalYear,
classes.ClassCode,
classes.Title
} into gcs
select new ClassUsageReport
{
ClassCode = gcs.Key.ClassCode,
Title = gcs.Key.Title,
Usage = gcs.Count(),
FiscalYear = gcs.Key.FiscalYear
}
);
return queryable.AsQueryable().OrderByDescending(x => x.FiscalYear).ThenByDescending(x => x.Usage);
}