Feel like a geek and get yourself Ema Personal Wiki for Android and Windows

08 October 2009

Checked propertynames in NHibernate queries

Automatic renaming of a property in VS2008 won't refactor the propertynames in NHibernate config files and queries. You will find out after running the unittests, of course, but I'd rather have a compile error, or, better, have VS2008 refactor the NHibernate config and queries too.

For the NHibernate config the reasonable alternative is to use Fluent NHibernate, which uses lambda's to get the propertynames.

For the queries you have to write such a solution yourself.

I have a base class for all entities that looks like this

public Entity<T> where T : Entity<T>
{
  public static string PropertyName(Expression<Func<T, object>> e)
  {
    UnaryExpression ue = e.Body as UnaryExpression;
    MemberExpression me = (ue == null ? e.Body as MemberExpression : 
      ue.Operand as MemberExpression);
    return me.Member.Name;
  }
}
After that I can use this method to get the propertynames in queries:
Criteria.Add(Expression.Eq(
  User.PropertyName(x => x.Emailaddress), "email@example.com"));
There are disadvantages. First, using Lambda expressions is slower than using the string value. Second, this only works for public properties. Third: in VB this will look very ugly. Until now, I can live with these disadvantages.

No comments: