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

3 comments:

Nice, looks like an easier syntax than my own solution.

Look so great!

However, I'm still confused about OR logic expression. Do you have any example about that?

There is some documentation in the project, and also hosted at: http://nhlambdaextensions.googlecode.com/files/NhLambdaExtensions.html

From the docs:

.Add(Expression.Or(
SqlExpression.CriterionFor<Person>(p => p.Name == "test"),
SqlExpression.CriterionFor<Person>(p => p.Age > 5)));