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.

simple_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.

invalid_transformer

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

empty_models

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.

alias_query

full_models

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.

typedresulttransformer

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

good_projection_query

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

postviewmodel

A small price to pay IMHO.

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

query_batch

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.

query_batch_executed

Nice! Open-mouthed smile

TrackBack

TrackBack URL for this entry:
http://www.typepad.com/services/trackback/6a0133ecbab7ab970b0147e076748c970b

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

Comments

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

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment