Search code examples
c#linqoracle11gfluent-nhibernate

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>();

Solution

  • 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.