NHibernate 3 – Part 1: Trying out the Linq provider

Using the new Linq provider is deceptively easy.

You still need to create some sort of context object that exposes the IQueryable<T> for each of your queryable domain objects.

Here is a simple one created for my BlogDemo project.


You can then inject this object into your controller and start writing you Linq queries against it.


One thing you should be aware of when using Linq is that the IQueryable<T> is a delayed enumerator, meaning that it will not execute until you start iterating through it.

So in the above code, the postQuery is just an IQueryable<PostViewModel> and nothing more. No hits to the database. The hit comes when you call an “executing” method such as “ToList” or “Count”. Here the query is executed when ToList is called with paging restrictions and again when Count is called without paging restrictions.

This becomes problematic when using with NHibernate as the “best practices” state that all queries should be executed in the scope of a transaction. If you do not call something like “ToList” then the query will be executed in the View which is outside the current transaction.

Another thing to be aware is that we are hitting the database three separate times.


I have not seen or figured out a way to batch Linq queries together, so if anyone does please let me know.

Have to say I really like writing queries this way. There are a couple things you need to be mindful of and you cannot batch queries together but the simplicity and readability of it make up for it.


TrackBack URL for this entry:

Listed below are links to weblogs that reference NHibernate 3 – Part 1: Trying out the Linq provider:


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.

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.


Post a comment