Sunday, January 17, 2010

No more magic strings in NHibernate 3.0

One of the many options to create and execute queries using NHibernate is the ICriteria API. A big disadvantage that makes refactoring harder is the use of magic strings to specify properties, etc.

   1:  .Add(Expression.Eq("Name", "Smith"))

NHibernate 3.0 introduces the QueryOver api, which combines the use of Extension Methods and Lambda Expressions  to provide a statically typesafe wrapper round the ICriteria API. It uses Lambda Expressions to provide some extra syntax to remove the 'magic strings' from your ICriteria queries.

So, the previous example becomes:

   1:  .Where<Person>(p => p.Name == "Smith")

With this kind of syntax there are no 'magic strings', and refactoring tools like 'Find All References', and 'Refactor->Rename' work perfectly.

Read more about this in Richard Brown’s great post.

No comments: