8

我正在将旧式查询重构CreateCriteria()QueryOver(). 我的 Wcf 服务可以string PropertyName订购查询结果。因为IQueryable我使用动态 LINQ 来进行这样的排序,对于CreateCriteria()- AddOrder()

IList<object[]> result =
            GetSession()
                .QueryOver(() => activity)
                .JoinAlias(() => activity.ActivityLicense, () => license)
                .Select(Projections.ProjectionList()
                            .Add(Projections.Count<Activity>(e => e.Id), "ActivityCount")
                            .Add(Projections.Group(() => license.SerialNumber), "SerialNumber")
                            .Add(Projections.Count<Activity>(e => e.MacAdress), "MacAddressCount")
                            .Add(Projections.Count<Activity>(e => e.IpAdress), "IpAddressCount")
                )
                .OrderByAlias("ActivityCount") // Compilation Error - I need such extension method
                .List<object[]>();

如果使用字符串属性名称,有什么建议如何进行排序?

PS:我无法使用 LINQ to Nhibernate:LINQ to NHibernate - .GroupBy().Skip().Take() 导致异常

谢谢!

4

2 回答 2

15

你总能得到UnderlyingCriteria...

var q = GetSession()
                .QueryOver(() => activity)
                .JoinAlias(() => activity.ActivityLicense, () => license)
                .Select(Projections.ProjectionList()
                            .Add(Projections.Count<Activity>(e => e.Id), "ActivityCount")
                            .Add(Projections.Group(() => license.SerialNumber), "SerialNumber")
                            .Add(Projections.Count<Activity>(e => e.MacAdress), "MacAddressCount")
                            .Add(Projections.Count<Activity>(e => e.IpAdress), "IpAddressCount")
                );


q.UnderlyingCriteria.AddOrder(new Order("ActivityCount", true));

var results = q.List();

或作为 IQueryOver 的扩展方法

public static IQueryOver<T,T> OrderByAlias(this IQueryOver<T,T> q, string aliasName, bool ascending)
{
    q.UnderlyingCriteria.AddOrder(new Order(aliasName, ascending));
    return q;
}
于 2012-08-13T14:47:04.270 回答
1

您可以通过传入 QueryOver API 直接设置 OrderBy Projections.Property(propName),例如:

var query = GetSession()
                .QueryOver<Activity>()
                .OrderBy(Projections.Property("ActivityCount").Desc;

无法通过字符串设置方向,因此您必须执行简单的 if/else 或创建扩展方法来简化 API。

于 2013-01-23T06:01:22.423 回答