Yet another post on my learning NHIbernate in public…. In an attempt to provide full disclosure I am a complete NOOBIE when it comes to NHibernate. In fact I have only been using it for a few weeks or so. What this means is take everything I say in this post with a grain of salt cause there may be a better, easier way.
Say you have a legacy database that has a nasty schema (yea, we all have seen these before) and you are stuck with many tables which have composite-id’s, what do you do? The good news for you is that you can easily map these with NHibernate very easily using the latest build of FluentNHibernate.
Take a look at the database tables below to gain a better understanding of what it is we are going to map.

The first thing we need to do is setup our mapping for the parent in this relationship (the one). The code below is the mapping for the InsuranceCompany entity.
public class InsuranceCompanyMap : ClassMap
{
public InsuranceCompanyMap()
{
WithTable( "A_INSURANCE_COMPANY" );
UseCompositeId()
.WithKeyProperty( x => x.AdminSetID, "ADMIN_SET_ID" )
.WithKeyProperty( x => x.CompanyCode, "COMPANY_CODE" );
// Removed standard property mapping
HasMany<InsuranceCompanyAddress>( x => x.CompanyAddresses )
.Access.AsCamelCaseField( Prefix.Underscore )
.WithKeyColumn( "Admin_set_id" )
.WithKeyColumn( "Company_Code" )
.IsInverse()
.LazyLoad();
}
}
There are 2 things we need to look at when trying to determine what is going on here
- The user of UseCompositeID. This is how you setup your mapping if the table has composite-id’s as its keys
- The details of the HasMany (one-to-many mapping). Pat attention how we used the WithKeyColumn multiple times. By using this multiple times you are telling Fluent-NHibernate to setup a the relationship as composite-id’s
Now that we understand the mapping for the parent (the one), we need to take a look at the child part (the many). The code below is the mapping is for the InsuranceCompanyAddress.
public class InsuranceCompanyAddressMap : ClassMap
{
public InsuranceCompanyAddressMap()
{
WithTable( "A_INSURANCE_COMPANY_ADDRESS" );
UseCompositeId()
.WithKeyProperty( x => x.AdminSetID, "ADMIN_SET_ID" )
.WithKeyProperty( x => x.AddressID, "ADDRESS_ID" );
// removed property mapping
References( x => x.InsuranceCompany )
.Access.AsCamelCaseField( Prefix.Underscore )
.WithColumns( "ADMIN_SET_ID", "COMPANY_CODE" )
.LazyLoad();
}
}
When taking a look at the mapping above there are 2 things we need to look at
- The user of UseCompositeID, this is how you setup our mapping for composite-id
- The use of WithColumns() on the References (many-to-one) mapping when trying to map back to the parent. This will tell NHibernate to use the composite-id as the mapping key.
There you have it, if your db schema is nasty and makes heavy use of composite-id’s rest assured because NHiberante and FluentNHibernate can allow you to simply and quickly setup your mappings.
Till next time,
Posted
01-30-2009 8:49 PM
by
Derik Whittaker