Chris F
Chris F

Reputation: 2946

Can I set NHibernate's default "OrderBy" to be "CreatedDate" not "Id"?

This is an oddball question I figure.

Can I get NHibernate to ask SQL to sort data by CreatedDate by default unless I set an OrderBy in my HQL or Criteria? I'm interested in knowing whether this sort can be accomplished at the DB level to avoid bringing in LINQ.

The reason is that I use GUIDs for Ids and when I do something like this:

Sheet sheet = sheetRepository.Get(_someGUID);
IList<SheetLineItems> lineItems = sheet.LineItems;

to fetch all of the lineItems, they come back in whatever arbitrary way that SQL sorts that fetch, which I figure is GUID. At some point I'll add ordinals to my line items, but for now, I just want to use CreatedDate as the sort criteria. I don't want to be forced to do:

IList<SheetLineItem> lineItems = sheetLineItemRepository.GetAll(_sheetGUID);

and then writing that method to sort by CreatedDate. I figure if everything is just sorted on CreatedDate by default, that would be fine, unless specifically requested otherwise.

Upvotes: 2

Views: 1061

Answers (2)

Jamie Ide
Jamie Ide

Reputation: 49271

No, you can't. The best solution (as you mention in a comment) is to set the order-by attribute in the collection mapping. Note that the value should be set to the database column name, not the property name.

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838666

You don't need to write a method to do the sorting, just use LINQ's OrderBy extension method:

sheetLineItemRepository.GetAll(_sheetGUID).OrderBy(x => x.CreatedDate);

You could put a clustered index on CreatedDate in the database and then you will probably get the records in this order but you definitely shouldn't rely on it.

Upvotes: 1

Related Questions