views:

60

answers:

1

Say you have a table named Articles.

It has the following columns: ID, name, body, created, modified, pageviews, etc.

Using a single method, would it be possible to pull a list of articles, and pass it which column I want to order by? And also the direction, i.e. desc or asc.

+2  A: 

I'm not sure what you mean by "single method" comment, but you can do this using Criteria:

IList articles = session.CreateCriteria(typeof(Article))
  .AddOrder( Order.Asc("Name") )
  .List();

Obviously, you can wrap this in a method and pass the name of the property you want to order by as parameter as well as sorting direction. The latter is specified by Order.Asc() or Order.Desc().

ChssPly76
of course, if you're more comfortable using HQL, the equivalent would be "from article order by Name asc"
joshua.ewer
@joshua.ewer - you're right, and using HQL is _usually_ a better approach. However, in this case HQL would have to be dynamically generated which is less than ideal.
ChssPly76