Recently Oren (Ayende) had a serious of posts on NHibernate mappings and the various options you can configure using Xml mappings. This series of posts takes those examples and shows how you can use FluentNHibernate to configure the same mappings.
This is a companion post for Oren’s post on the <one-to-one> mapping in NHibernate, here. I recommend reading his post before venturing forward.
In FluentNHibernate one-to-one mappings are achieved by using the HasOne mapping method on the parent and the References method on the child. Below is the mapping for the Person entity that has a one-to-one relationship with an Employee entity:
HasOne(prop => prop.Employee)
.PropertyRef(prop => prop.Person);
You can also specify the actual property that HasOne uses to specify the foreign key relationship using the PropertyRef method. The above statement basically creates a mapping instruction that reads “Person has a one-to-one relationship with Employee on the Person property of the Employee entity”.
Similarly, the Employee mappings use the References mapping method to specify the bi-directional part of the relationship. Here’s the full class mapping for Employee:
public class EmployeeMap : ClassMap<Employee>
Id(prop => prop.Id).GeneratedBy.Native();
Map(prop => prop.Role);
References(prop => prop.Person)
The References mapping method in EmployeeMap generates a many-to-one mapping to the Person entity. You must add the Unique mapping modifier to instruct that the many-to-one mapping maps to a unique Person instance making it effectively a one-to-one mapping. You’ll also notice that I’ve set the FetchType to Select, this is done so that associated Person instances are lazy loaded when needed.