I have the following code which counts vehicles grouped by vehicle type.
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;
}
The above produces the following sql code:
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
The SQL code runs perfectly well under MS SQL Server but testing under SQl CE it produces the following error:
System.Data.SqlServerCe.SqlCeException : Expressions in the ORDER BY list cannot contain aggregate functions.
A solution from Sub query in Sql server CE is to specify an alias for the column and use the alias in the order by clause.
Is there any way to provide an alias in the LINQ expression that I am using to enable it run without raising errors?
You can perform the OrderBy in memory, with LINQ to objects: