Jan 23, 2009 / nhibernate
Release It! OpsDb Implementation with Fluent NHibernate Auto-Mappings

Last night I read all about operations databases in the Release It! book. I wish I'd read it 5 years ago. An OpsDb should allow you to monitor, analyze and forecast system stability.

This morning, after releasing James Gregory from Skype to go play with his brand new XBox 360, I thought I'd try and learn his Fluent NHibernate library.

I set out with a simple task - to model the prescribed Release It! OpsDb model in C# using Fluent NH.

Here's the entities in OpsDB C# for observations. Download VS solution.

Picture of OpsDB C# Model in .NET

Check the code below. In just 20 lines of code I managed to map 7 entities, fluently configure NHibernate and generate the database. No XML or Mapping Attributes at all in this solution. None. Sweee-eeee-eeee-t!

The model is moderately complex too (from a mapping perspective): All entities inherit from a layer supertype (Entity), and some entities have deeper inheritance. There's also one-to-many associations, and a many-to-many association (taken care of by a nifty patch by Ayende - ta!)

public void BeforeFixureStarts()
    var autoMappings =
            .Where(t => t.Name == "Entity" || t.Namespace.StartsWith("Pulse.OpsDB.Model") && t.Name != "Observation")

    var conf = new Configuration();

        .ConnectionString.Is("Server=;Initial Catalog=OpsDB_Test;Integrated Security=True")

    _factory = conf.BuildSessionFactory();

    new SchemaExport(conf).Drop(false,true);
    new SchemaExport(conf).Create(false,true);

This all makes me a bit giddy. Entire models can be mapped in almost ZERO man hours. It's like Rails ActiveRecord, but possibly even better.

In all fairness, there was a learning curve with all this. It probably took me about 10 minutes to implement the entities from Releases It!, and about 3 hours to figure out how to get the auto-mappings working and side-step a few unexpected issues. So, there's a small way to go yet.

In case you're wondering, the issues I side-stepped were a) Observation being added to the mapping multiple times (probably due to inheritance) and b) An entity which has an association to it's own type was having duplicate Id issues. More time was spent figuring out the current best way the fluent interface handled some things (I was thrown off track by some older articles online). Anyway, I got there in the end, and next time it will be loads quicker to get started! Fantastic!

Note #1: I was going to name this article *Fluent NHibernate AutoMap is A.W.E.S.O.M.E.*

Note #2: You can download the Visual Studio solution here (bear in mind it's only work in progress)

You may also like...