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 <set> mapping in NHibernate, here. I recommend reading his post before venturing forward.
A <set> element in NHibernate’s mapping refers to a one-to many mapping. This can be represented simply in FluentNHibernate using the HasMany mapping method:
HasMany(prop => prop.Comments);
The HasMany statement simply specifies that the entity has a one-to-many relationship with the Comment entity as represented by the Comments property.
Specifying the foreign key name.
If you need to specify the foreign key column on the relationship you can use the KeyColumnNames property and use the Add method to specify the column name:
HasMany(prop => prop.Comments)
.KeyColumnNames.Add("CreatedBy");
The above code snippet shows that the foreign key column on the Comments relationship is named “CreatedBy”.
Fetching strategy for relationships:
By default the fetching strategy used by fluent-nhibernate for associations is not lazy loaded (for auto mapping the convention is to set lazy as true). You can override this behavior using the Lazy method
HasMany(prop => prop.Comments)
.KeyColumnNames.Add("CreatedBy")
.LazyLoad();
To specify that the collection should be loaded using an outer-join, use the FetchType property on the mapping. This mapping can be either; Select or Join. The first one is the default setting which uses a sparate Select statement to get the associated entities, whereas Join uses an outer join statement to get the associated entities.
HasMany(prop => prop.Comments)
.KeyColumnNames.Add("CreatedBy")
.LazyLoad()
.FetchType.Join();
Note that when you specify FetchType as Join, even if you specify LazyLoad NHibernate will still pre-fetch the entities using a left outer join.
Defining an inverse relationship:
Inverse is specified by simply setting the association as Inverse()
HasMany(prop => prop.Comments)
.KeyColumnNames.Add("CreatedBy")
.LazyLoad()
.FetchType.Join()
.Inverse();