Mapping an unrelated class in Fluent NHibernate

There are times when you will need to map unrelated classes through fluent nhibernate. By an unrelated class, I mean a class which is not directly mapped to a database table. This is useful when you create DTOs (Data Transfer Object) for a lightweight object to pass around in your application. Consider the following – you have an Employee class with Id, Firstname, Lastname, DoB, Marital Status, JoinedDate, DeptId. Now in your presentation layer, if you just need to display the Id and Lastname of the employee, you might consider writing a subclass of Employee and called it EmployeeDTO which has only Id and Firstname as fields. This is just to simplify things.

Your Employee class will be mapped to your Employee table through EmployeeMap. To map the EmployeeDTO, you will need to use ImportType in fluent nhibernate as follows:

public class EmployeeMap : ClassMap<Employee>
 public EmployeeMap()

 Id(x => x.Id);
 // rest of your mapping here

With this in place, your unrelated class is now mapped to your Employee class.

How to fetch data in a class which is not directly mapped to a table in fluent nhibernate?

public virtual IList<EmployeeDTO> FindEmployees(ISession session)
 IQuery query = session.CreateQuery("select new EmployeeDTO(E.Id, E.Firstname) from Employee as E WHERE E.DeptId = :deptid");
 query.SetParameter("deptid", 1);
 return query.SetMaxResults(5).List<EmployeeDTO>();

Notice that the above query is using HQL (Hibernate Query Language) and is already casting the result to EmployeeDTO type which means you’re getting back a strongly typed object and also we’re using parameterised queries to prevent sql injection.

comments powered by Disqus