tags:

views:

80

answers:

2

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.

+1  A: 

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.

Mark Byers
Or `IEnumerable<SheetLineItems> lineItems = sheet.LineItems.OrderBy(x => x.CreatedDate);`
Martinho Fernandes
@Mark I thought of the LINQ technique too, and was just hoping to avoid using it and get the DB to do it for me.@Martinho Yeah, I actually do exactly what you wrote now, but thought I should ask the community if there is a better way to get the DB to just do it for me.
Chris F
@Chris: you can make that part (can/should the DB/NHibernate do it for me?) more explicit in the question. I will be interested in the answers.
Martinho Fernandes
A: 

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.

Jamie Ide