简体   繁体   中英

How to add dynamic sort by direction to NHibernate queryover

I am trying to add dynamic order by direction to my nhibernate queryover. Can anyone help how to do this? I was able to add dynamic orderby field. 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.

So then you could apply the

  • OrderBy() which:

Sorts the elements of a sequence in ascending order according to a key.

  • OrderByDescending() which:

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 .


As requested by OP in comments, added sample generic code:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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