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:

        .Add(Expression.Eq("Name", "smith"))

... turns into code like:

        .Add<Person>(p => p.Name == "smith")

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


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:

From the docs:

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