Fluent NHibernate’s AutoPersistenceModel: I Love it!

I checked out the latest version of Fluent NHibernate today and noticed the AutoPersistenceModel. I looked at the unit-tests to see what it’s supposed to do and I loved what I saw!

Let’s say you have a 2 simple classes like this:

image

Now, in the global.asax’s init (assuming a web application), we can configure NHibernate using Fluent NHibernate like this:

image

It uses convention over configuration in lots of places, eg the Id property is always used as identity-column if a property with that name exists.
But you could also easily add your own conventions. If you want to have the Id colums to be ArtistId and AlbumId (and any other className + Id), you’d do:

image

Want to restrict the namespace as well? No problem!

image

Fantastic! Now, to see what mapping file this code automagically creates for our Artist class, we can run the following code:

image

which returns an XmlDocument. In this case, the InnerXml of that document looks like this:

image

Again: fantastic! See how it even generates the one-to-many relation with the correct end-class, because we defined a property IList<Album>!

Running the same code for the Album class gives:

image

If you want to use Fluent NHibernate the ‘old’ way, you can still add ClassMap<Artist> to your assembly. Hence, you can even mix it with the AutoPersistenceModel! If you have a classmap file, it’ll use that for your class, if it isn’t there it’ll automatically create a mapping for you!

I’m sold! This makes using NHibernate a breeze. You can get up and running with your NHibernate project so much faster now.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.