FluentNHibernate And NHibernate.Linq

Just a little blurb on FluentNHibernate and NHibernate.Linq.

I’ve been working through the samples for FNH and decided to try out some different query scenarios to see how the queries would be generated. I stumbled a bit on the first rather simple scenario: selecting an item based on the total count of related items. In this case, from the FNH demo, I wanted to select “all stores with more than 2 employees”. Seems like a simple enough query, right?

You can see from the full code that this should return “Bargain Basement”. However, in going through the documentation, it wasn’t exactly apparent how this could be done; it seemed a lot more convoluted than necessary using criteria queries and it simply wasn’t working. Via Google, I came across a blog post that mentioned using either DetachedCriteria or HQL. Quite frankly, neither was very appealing.

So I figured I’d download NHibernate.Linq and see if it would be better. Not knowing what I would get, SQL-wise, I wrote the following query:

Of course, the interesting question is whether the the Staff list would be loaded to perform the count and to my pleasant surprise, it was not. Here’s the query in profiler (reformatted for legibility):

Sweet! The framework correctly builds a sub-select query to count the staff members.

I guess I’m just easy to impress 🙂 but I’m digging it.

I think what I like about FluentNHibernate the most is that I can stop building database applications. What I mean by this is an application built from the database up. The main issue this raises is complexity with regards to mapping to a data layer and of course continuously having to synchronize your DDL and SQL with your class files. The following code configures the database, including dropping and creating the tables based on mapping classes in my assemblies:

With no mapping files to speak of, persistence plumbing becomes trivial and I can work entirely within Visual Studio. Of course, for complex queries and queries that need to be highly performant, you may still be better off writing stored procedures (as I’ve advocated in the past), but the productivity gains to be had can’t be ignored and I find the compile-time validation of the queries eases some of my indifference towards dynamic SQL.

You may also like...

1 Response

  1. G F Mueden says:

    our copy is on my screen in the font my IE8 says I want.. Not so with the code. The code is in a much smalled fait font. If you (anybody) emails me and asks for "for Charlie", I will send a screenshot showing the difference. gfmueden@verizon.net