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 <join> mapping in NHibernate, here. I recommend reading his post before venturing forward.
To create a joined table mapping using FluentNHibernate you need to use the WithTable mapping function and specify the JoinedPart definition:
WithTable("Addresses", join =>
{
join.Map(prop => prop.StreetAddress1, "StreetAddress1");
join.Map(prop => prop.StreetAddress2, "StreetAddress2");
join.Map(prop => prop.City, "City");
join.Map(prop => prop.State, "State");
join.Map(prop => prop.ZipCode, "ZipCode");
join.WithKeyColumn("PersonId");
});
The WithTable mapping function has two overloads, one just taking in a string parameter and another that takes in a string parameter as well as a action that allows you to configure a JoinPart. The first overload instructs fluent nhibernate to output the table name of the class being mapped, for e.g WithTable("Persons") will generate a mapping: <class name="Person" table="Persons"> element.
The second overload outputs the <join> element in the mapping. Just like mapping a component, the JoinPart allows you to map properties in the class as belonging to another table. The only thing to be aware of here is that you are specifying the column names in the join table for your properties manually.
Now to define the join table as optional, you again need to use the SetAttribute method to output the "optional" attribute since there's no inbuilt way to specify that in the JoinPart. Below is the full mapping:
WithTable("Addresses", join =>
{
join.Map(prop => prop.StreetAddress1, "StreetAddress1");
join.Map(prop => prop.StreetAddress2, "StreetAddress2");
join.Map(prop => prop.City, "City");
join.Map(prop => prop.State, "State");
join.Map(prop => prop.ZipCode, "ZipCode");
join.WithKeyColumn("PersonId");
join.SetAttribute("optional", "true");
});