tags:

views:

51

answers:

1

Came across something like this today, and was wondering if there was an equivalent way to solve it in criteria queries.

Basically, there is a table, and this table has two nullable string fields (foo and bar). We wish to sort by the aggregate of these.

string concatenation (order by foo + bar desc) returns null if one of the values is null, and order by foo, bar doesn't take into account nulls as we wish.

a solution in sql could look like :

SELECT foo, bar, (ISNULL(foo,'') + ISNULL(bar,'')) as f
FROM foobar
ORDER BY f DESC

I'm not sure of the details within nhibernate's tokenizer, but if you were to write it as

SELECT foo, bar
FROM foobar
ORDER BY (ISNULL(foo,'') + ISNULL(bar,'')) DESC

using the same query method it chokes because it parses both foo and bar as individual sort expressions.

So...how would you write that in a criteria query? Is there such a method, or would a new ResultTransformer or after-the-fact sorting be the only option?

+2  A: 

You should create query-only properties (access="noop", see http://ayende.com/Blog/archive/2009/06/10/nhibernate-ndash-query-only-properties.aspx) with the corresponding formula.

For example,

<property name="SortableFoo" formula="ISNULL(foo,'')"/>

And you can now AddOrder with that "Property".

Diego Mijelshon
very interesting. Sad to see that the solution seems to be at the binding level rather than the criteria level though =/
ddango
Actually, I think it _can_ be done using Projections, SQLFunctions and that kind of stuff... but I think it's even more complicated.With HQL, on the other hand, it shouldn't be much different from the SQL. Have you tried that?
Diego Mijelshon