NHibernate detached OrderBy
-
14-06-2021 - |
Question
I am using a repository pattern to wrap NHibernate entities. One of the methods is public IList<T> GetAll()
which simply returns all items of that entity. The implementation is done in either Criteria or QueryOver.
I would like to overload this method to accept a sorting order, something like this: public IList<T> GetAll(NHOrderFor<T> order)
which I could call and fluently define the order for. Is this possible? QueryOver is preferred but not required.
Update
I got a little further ahead. I defined the parameter as Expression<Func<T,object>> path
which is what's expected by QueryOver.OrderBy() but the expression is missing the .Asc or .Desc
specification that's required to follow.
Solution
You can pass in a bool variable to determine if it's asc or desc - the only "tricky" part is that the .Asc and .Desc are properties, so you have to assign them to a result (you don't need to do anything with the result tho - it just returns the same queryover), eg:
public IList<T> GetAll(Expression<Func<T,object>> path, bool ascending) {
if (ascending)
queryOver = queryOver.OrderBy(path).Asc;
else
queryOver = queryOver.OrderBy(path).Desc;
return queryOver.List<T>();
}