简体   繁体   English

如何向NHibernate queryover添加按方向动态排序

[英]How to add dynamic sort by direction to NHibernate queryover

I am trying to add dynamic order by direction to my nhibernate queryover. 我试图将方向动态顺序添加到我的nhibernate queryover中。 Can anyone help how to do this? 谁能帮忙做到这一点? I was able to add dynamic orderby field. 我能够添加动态orderby字段。 but dont know how to do the order by direction. 但不知道如何按方向进行排序。 Please find below my code: 请在下面找到我的代码:

    if (!string.IsNullOrEmpty(sortField))
    {
        var sortByProperty = Helper.GetSortByProperty(sortField);
        if (sortByProperty != null)
        {
            query.OrderBy(x => sortByProperty.GetValue(x, null));
        }
    }

    var result = query.Skip(pageIndex*pageSize)
                        .Take(pageSize)
                        .Future<Member>();

The way I have done this is, passing in a ListSortDirection type variable to the function that is doing the query. 我这样做的方法是,将ListSortDirection类型变量传递给正在执行查询的函数。

So then you could apply the 因此,您可以应用

  • OrderBy() which: OrderBy()

Sorts the elements of a sequence in ascending order according to a key. 根据键以升序对序列的元素进行排序。

  • OrderByDescending() which: OrderByDescending()

Sorts the elements of a sequence in descending order according to a key. 根据键以降序对序列的元素进行排序。

on your IQueryable<T> depending on the values from ListSortDirection.Ascending or ListSortDirection.Descending . IQueryable<T>上,具体取决于ListSortDirection.AscendingListSortDirection.Descending的值。


As requested by OP in comments, added sample generic code: 根据OP在注释中的要求,添加了示例通用代码:

public IList<T> GetEntityList<T>(Expression<Func<T, bool>> whereExpression, Expression<Func<T, object>> orderByExpression, ListSortDirection orderDirection, int totalPages, int start, int limit)
{
    IList<T> returnVar;
    using (var session = _nhibernate.OpenSession())
    {
        var firstQueryable = session.Query<T>().Where(whereExpression);

        IQueryable<T> secondQueryable = orderDirection == ListSortDirection.Ascending ? firstQueryable.OrderBy(orderByExpression) : firstQueryable.OrderByDescending(orderByExpression);

        returnVar = totalPages > 0 ? secondQueryable.Skip(start).Take(limit).ToList() : secondQueryable.ToList();    
    }

    return returnVar;
}


To address another question in comment from OP, for the QueryOver API, for instance you can use the .OrderBy(orderByExpression).Desc for reverse sorting. 例如,要解决OP的注释问题,可以使用QueryOver API的.OrderBy(orderByExpression).Desc进行反向排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM