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.

dbcontext

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

linq

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.

linq_queries

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

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

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

Comments

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

The comments to this entry are closed.