Friday, July 30, 2010

Dynamic mapping for NHibernate

In most ORM solutions, you have to create some mapping between your tables and columns in your database and the objects and properties in your domain.

Entity Framework allows you to this through a designer, NHibernate has XML support and some Fluent Mapping options. You can even start introducing conventions to minimize the amount of mapping needed.

But of course, lazy as we are, in some occasions this is still too much work. So if you have some simple objects and some simple queries, another option is available for you; NHibernate transformers.

NHibernate transformers  are used to transform the results of the query into something useful. 

To give you an example, imagine I have a simple product class:

   1:  public class Product
   2:  {
   3:      public string ID{ get; set; }
   4:      public string ProductName{ get; set; }
   5:  }

I’ll can create a simple SQL query and let NHibernate do the mapping for me by calling the AliasToBean transformer:

   2:  var session=SessionFactory.GetCurrentSession();
   3:  var query = session.CreateSQLQuery(sql);
   5:  var results = query 
   6:      .SetResultTransformer(Transformers.AliasToBean(typeof(Product)))
   7:      .List<Product>();

The AliasToBean method is a factory method on the static Transformers class.   I don’t have to specify any additional mapping file.

So this is very useful feature when you just want to map any table into a DTO, as long as the DTO matches up well to the underlying query results.

No comments: