Fluent NHibernate Mapping Identity Columns to Properties

by jmorris 1. December 2009 06:37

I decided to jump into the NHibernate lovefest and use it in an upcoming project that I am planning right now. I have been following the NHibernate project for some years, but never actually comitted to using it in a project, because frankly, it was a bit intimidating in size and complexity. Now, of course this was my biased assumption and boy was I wrong! The new Linq 2 NHibernate and Fluent NHibernate API's are awesome and relatively simple to get up and running.

Although I still have some reservations about the completeness and performance of Linq 2 Hibernate, Fluent NHibernate seems to be pretty mature. Additionally, the Fluent NHibernate community is robust, friendly and very quick to lend a hand when I ran into some trouble with AutoMapping.

AutoMapping is a convention based feature of Fluent NHibernate in which with a very little configuration, you can map your entire schema to your domain model. This feature is a tremendous time saver, and gives the illusion of "it just works"! As awesome AutoMapping is, there are certain situations where it will choke. In these cases you must add a little "help" to make the mapping work correctly. Take the following table:


Just your basic Role table, but notice how the primary key column is named [entity name]+Id: RoleId? This is a convention that I use for naming the primary keys of all tables I create. It is simple, easy to understand, and works! Now here is the domain model object that it maps to:


Notice that the domain object does not have a field called RoleId? Instead we have another field in our base called Id. Now seeing how AutoMapping requires convention (namely naming conventions) to map entities, how does Fluent NHibernate map this with AutoMapping? Well, unfortuntaly it can't:


However, with a little help from the Constraints API, we can easily resolve this mapping with a minimum amount of code. What are Conventions, you might ask? According to the Fluent Nhibernate documentation:

"Conventions are small self-contained chunks of behavior that are applied to the mappings Fluent NHibernate generates. These conventions are of varying degrees of granularity, and can be as simple or complex as you require. You should use conventions to avoid repetition in your mappings and to enforce a domain-wide standard consistency."

Connventions are a set of base classes and interfaces that when implemented, allow you to override the default AutoMapping behaviour. Pretty sweet. 

Ok, so how did I resolve the mapping exception above? First the Covention implementation:

And finally the configuration with Fluent NHibernate AutoMapping API:

Tags: , , ,

Jeff Morris

Tag cloud

Month List

Page List