SqlCeException - ORDER BY列表中的表达式不能包含聚合函数

时间:2012-08-17 21:42:29

标签: sql-server linq nhibernate

我有以下代码来计算按车辆类型分组的车辆。

using (var uow = new UnitOfWork(new NHibernateHelper().SessionFactory)) {
    var repo = new Repository<Vehicle>(uow.Session);
    var vtSummary= repo.ListAll()
                .GroupBy(v => v.VehicleType.Name)
                .Select(v => new NameCount { 
                         EntityDescription = v.First().VehicleType.Name,
                         QtyCount = v.Count() })
                .OrderByDescending(v => v.QtyCount).ToList();
     uow.Commit();
     return vtSummary;
}

以上产生以下sql代码:

SELECT VehicleType.Name as col_0_0_,
   CAST(COUNT(*) AS INT) as col_1_0_
FROM Vehicle vehicle0_
LEFT OUTER JOIN VehicleType vehicletype1_
  ON vehicle0_.VehicleTypeId= VehicleType.Id
GROUP  BY VehicleType.Name
ORDER  BY CAST(COUNT(*) AS INT) DESC

SQL代码在MS SQL Server下运行良好,但在SQl CE下进行测试会产生以下错误:

System.Data.SqlServerCe.SqlCeException : Expressions in the ORDER BY list cannot contain aggregate functions.

来自Sub query in Sql server CE的解决方案是为列指定别名并在order by子句中使用别名。

有没有办法在LINQ表达式中提供别名,以便在不引发错误的情况下运行它?

1 个答案:

答案 0 :(得分:1)

您可以使用LINQ to objects执行内存中的OrderBy:

var vtSummary= repo.ListAll()
            .GroupBy(v => v.VehicleType.Name)
            .Select(v => new NameCount { 
                     EntityDescription = v.First().VehicleType.Name,
                     QtyCount = v.Count() })
            .AsEnumerable() //SQL executes at this point
            .OrderByDescending(v => v.QtyCount).ToList();