NHibernate 3 – Part 2: Strongly typed Criteria with QueryOver

While you have been able to create strongly typed Criteria objects with the nhlamdaextensions project, the release of NHibernate 3 brings the official implementation with QueryOver.

One of the cool things regarding QueryOver is that almost anything you could do with a Criteria object you can do with a QueryOver object including batching, projections and have detached objects.

Creating a simple detached QueryOver is as simple as the following snippet.


Projections are slick as well although getting a typed projection can be a bit of a pain. For example, to get a PostEntity projected onto a PostViewModel you need to use a Transformer. NHibernate ships with an AliasToBean transformer that at first I thought would work nicely.


When I execute this code I get results back but the models are empty.


The problem can be identified by paying closer attention to the name of the transformer. It is an “AliasToBean” transformer and I have not supplied any aliases.

If I do alias the fields the transformation will work.



I don’t know about you but I think aliasing like that looks like crap.

Instead I tried out the TypedResultTransformer that I shameless stole from Ayende’s Rhino.Commons library a long time ago.


Now I can use this transformer instead of the AliasToBean transformer and don’t need to worry about aliasing the fields.


The gotcha with this method is that it requires a constructor in you projection object with all the properties.


A small price to pay IMHO.

Did I mention that queries can be batched? I love being able to do this.


The queryBatch object is a simple object to make batching the queries easier. I will discuss it an a future post, but the result of this is three statements executed in one trip to the database.


Nice! Open-mouthed smile


TrackBack URL for this entry:

Listed below are links to weblogs that reference NHibernate 3 – Part 2: Strongly typed Criteria with QueryOver:


You can follow this conversation by subscribing to the comment feed for this post.

The comments to this entry are closed.