Tag Archives: C#

NHibernate Attributes

I am using NHibernate for some years now, mainly to integrate an existing database into the new shiny .NET version of the application while it is still being used by a legacy application.
It’s served very well as an integration technique saving me from headaches more than once. Especially when moving from MS SQL Server to Oracle to MySQL while attracting more customers to the application.
Thus, I use mapping files which are deployed alongside the application in order to make the odd adjustment for some customers. That doesn’t happen very often, but it does.
Recently I had the chance to start a new application. Besides all of the advantages, writing mapping files CAN get a little bit tiring when creating new data model classes. That’s where NHibernate Mapping Attributes come into play.
The concept is quite straight forward. You add a lot of annotations to your data class and during application startup the library creates the mapping infomation in memory and configures NHibernate accordingly. It could actually be a little more directly, but it works just fine.

Configuration cfg = new Configuration();
HbmSerializer.Default.Validate = true;
MemoryStream ms = HbmSerializer.Default.Serialize(System.Reflection.Assembly.GetExecutingAssembly());

The argument of the Serialize() method could be any other assembly if you like. For my prototype it was the executing assembly. After that bit, it’s just the usual NHibernate process of creating the SessionFactory and getting the Sessions from the SessionFactory.
Creating a persistent class is just as easy.

using NHibernate.Mapping.Attributes;

public class Something
[Id, Generator(Class="assigned")]
public int Id{ get; set; }

public String Name { get; set; }

The attributes are quite self-explanatory and if you are used to writing mapping files it is quite natural.