NHibernate Query Generator

by benl

We should all be more than familiar with useful tools and commits coming from Ayende by now 🙂 However, the one I really dig is his NHibernate Query Generator.

NHQG is a console application which when pointed at your NHibernate mapping files, produces a bunch of partial classes for the types in your domain model which ultimately generate NHibernate DetachedCriteria. The real goodness is in the expressiveness of the querying API which they create.

Consider the following traditional NHibernate code:

IQuery query = session.CreateQuery("from Publisher as pub where pub.Name = :Name and pub.City = :City");
query.SetParameter("Name", "Test");
query.SetParameter("City", "London");
return query.List<Publisher>();

Using the NHQG generated helpers we can express this as:

return Repository.FindAll(
    (Where.Publisher.Name == name) && 
    (Where.Publisher.City == city));

Via nifty operator overloading and generics magic we end up with the Where syntax. Obviously this example just touches the surface of what we can do but don’t you agree how nice the 2nd approach is. The generated code supports navigating the relationships, ordering etc as you would expect.

Ayende prefers the no-strings approach. I tend to agree!

Advertisements