Broloco

I'm a big fan of NHibernate, and also of its Query Object the ICriteria API. I don't much care for 'magic strings' in my code though.

LINQ provides a way to strongly type your queries, but there are still times when you want an opaque query language with an object-oriented interface.

With .Net 3.5 came Lambda Expressions, which allow you to strongly type the individual expressions in a query. I started writing some extension methods to allow me to use lambda expressions with ICriteria, so code like:

mySession
    .CreateCriteria(typeof(Person))
        .Add(Expression.Eq("Name", "smith"))
        .List<Person>();
        

... turns into code like:

mySession
    .CreateCriteria(typeof(Person))
        .Add<Person>(p => p.Name == "smith")
        .List<Person>();
        

There turned out to be quite a few extension methods to write to cover all the different combinations of ICriteria that can be written (including DetachedCriteria, aliases, subqueries, ...) I've packaged it into a project on Google Code for anyone who wants to use it:

Submit this story to DotNetKicks Shout it