Wednesday, December 15, 2010

Using Conventions in NHibernate

Case: When your DB tanle name conventions and C# class name conventions are different,then to create map between these two, we can create conventions.

Step 1: Create a domain level attribute to define DB table for each C# class we need to map.

public class MyAttribute :Attribute
{
       public MyAttribute(string tableName)
       {
             TableName=tableName;
        }
       public string TableName{get;set;}

}

step 2: Declare TableName attribute on domain object
[MyAttribute("Employee_Details")]
public class Employee
{
      public virtual string Name{get;set;}
      public virtual long SSN{get;set;}
}

step3: Create convention

public class TableNameConvention : IClassConvention
step 4: Hook convention to NH configuration

var configuration=AutoMap.AssemblyOf<Employee>()
                           .conventions.Add(typeof(TableNameConvention))
{
    public void Apply(IClassInstance instance)
    {
         instance.table(SetTableName(instance));
    }
    private string SetTableName(IClassInstance instance)
    {
       var attributes = instance.EntityType.GetCustomAttributes(false);
       foreach(var attribute in attributes)
       {
          if(attribute is MyAttribute)
          {
             return ((MyAttribute)attribute).TableName;

}
           }
        return instance.EntityType.Name;

}
}
}