EDIT: Please note that this way of configuring Fluent NHibernate is obsolete since the RCs. Look here for an example on how to customize the automapping on Fluent NHibernate 1.0 RTM.

Fluent NHibernate is cool because there is too much XML in the world – so I appreciate any initiative to bring down the amount of XML. Configuring NHibernate using simple code and strongly types lambdas is actually pretty cool.

However, there is also too much code in the world – therefore, the AutoPersistenceModel is my preferred way of configuring Fluent NHibernate. It allows me to focus on what really matters: my domain model.

But don’t you lose control when all your database mapping is done automatically adhering only to a few conventions? No! You can always customize your mappings and complement/override the auto mappings. But then we can easily end up customizing too much, and then we are back to writing too much code.

Therefore, I would like to show how I use attributes to spice up my NHibernate mapping and add that tiny bit of extra customization that I need. I would like to be able to make the following entity:

That is, I want to be able to describe some extra mapping related stuff by applying a few non-instrusive attributes in my domain model.

How can that be accomplished with Fluent NHibernate? Easy! Like so:

and then I have made the following attributes:


UniqueAttribute.cs (works with ordinary as well as composite unique constraints):



If you are an extremist PI kinda guy you might think this is wrong – and I might agree with you a little, but I am also a pragmatic kinda guy, and I think this is a great compromise between being fairly non-intrusive but still expressive, effective and clear.

Customizing the NHibernate mapping when using the AutoPersistenceModel of Fluent NHibernate

4 thoughts on “Customizing the NHibernate mapping when using the AutoPersistenceModel of Fluent NHibernate

  • 2009-09-01 at 00:09

    Mookid, Do you have any idea how to create clustered indexes with Fluent NHibernate using auto mapping?

  • 2009-09-01 at 07:10

    Yes, that is what I am doing with the [Indexed] attribute. However, the way I’m doing it here does not work anymore because of changes in Fluent NHibernate. Now, I would probably create an IPropertyConvention implementation that looks for the attribute.

  • 2009-09-01 at 07:21

    Um, sorry – I am of course creating non-clustered indices here, because a clustered index is the physical order of data in the db, and that one is set by the PK.

  • 2009-09-01 at 09:47

    I understand. They added an Index() method on IPropertyInstance but did not provide an overload to optionally make it clustered. Maybe I will suggest this. Thanks for the feedback.


Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: