Aug 13 2009

Generic EnumString Mapping in NHibernate 2.1

Category: zvolkov @ 18:56

Some of us, geeks, have very good karma. Take for instance, Ayende or Hanselman -- these guys seem to live in the future (or is it we who live in the past?) -- no .NET 1.1 apps, no VB6 maintenance, no legacy databases. Legacy databases? What about them? Well as it often happens, legacy databases were grown (not built!) by legacy programmers. And as much as I love legacy programmers, I can't understand their fondness of varchar fields. I guess it's all about extensibility. And flexibility. Indeed, how do you extend your schema if not by making your DataProvider field a varchar, even if you will only ever have 3 distinct values in it.

The good thing about NHibernate, is how it isolates me from the legacy database, and the legacy programmer, along with legacy DBA and legacy PM :) Specifically, I like the ability to map ugly schema to er... almost elegant... object model.
One little tiny aspect of that is mapping varchars to enums.

In the past (where most of us live), that is in NHibernate 2.0, how did we map Enum property to a varchar column? By creating a mapper class like so:

public class GenericEnumMapper<TEnum> : EnumStringType
{
    public GenericEnumMapper() : base(typeof(TEnum))
    {
    }
}

Then, in your mapping file, oh miracle!, you could do something like this:

<property name="DataProvider" column="DataProviderConst" type="My.Namespace.GenericEnumMapper`1[[My.Namespace.DataProvider, My.Namespace]], My.Assembly">

In fact, this is exactly how it works in Fluent NHibernate (I know for sure, cuz that's where I stolen my from). There, you don't even need to define your mapper type. Just do Map(x => x.DataProvider, "DataProviderConst").CustomTypeIs<DataProvider>(); and you're all done. But, I don't use Fluent NHibernate. In fact, I don't even recommend it. That's why I was glad to see how NH 2.1 included built-in support for Generic EnumString Mapping. Not that the 2.0 way bothered me that much, but, as a true Kaizen practitioner, I always welcome [meaningless] improvements.

To make your life easier, and reduce your learning curve (I'm being satirical here, likely under the influence of Remy Martin), today I gonna show you how to do this trick in NH 2.1. The thing is, there's now a built in type EnumStringType<T>, which works exactly like our GenericEnumMapper above.  All you need to do is:

<property name="DataProvider" column="DataProviderConst" type="EnumStringType`1[[My.Namespace.DataProvider, My.Namespace]]">

And you are done. What an improvement! Hurray! Cheers! Long live the king! 

Tags:

Comments

Add comment


(Will show your Gravatar icon)

biuquote
  • Comment
  • Preview
Loading