Customizing the NHibernate mapping when using the AutoPersistenceModel of Fluent NHibernate

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:

IndexedAttribute.cs:

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

LengthAttribute.cs:

EncryptedAttribute.cs:

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.