Using enums in the NHibernate designer

NHibernate has the facility to map integer columns in the database to enum values in your objects. However, the NHibernate Designer doesn’t automatically know about your enum types, so by default you won’t find your enum types in the Data Type drop-down. So if you want to map a column an enum, how do you do it?

The answer is that you need to tell the NHibernate Designer about your enum type, which you can do through the NHibernate Model Explorer. To open the NHibernate Model Explorer if it’s not already open, choose View > Other Windows > NHibernate Model. You’ll see a tree display of your model.

Now right-click the Model node and choose Add New Enum Type. Then enter the full enum type name, and the name by which you want to refer to the enum in the Data Type drop-down:

Now you can use the enum type in your entity properties just as if it were a built-in type:

Download the NHibernate designer today — or install it directly through the VS2010 Extension Manager — and check it out!

6 Responses to “Using enums in the NHibernate designer”

  • Using enums in the Mindscape NHibernate Designer…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…

  • When will this be in the LightSpeed designer? :D

  • Hello Johan,

    You can already do this in the LightSpeed 3.1 designer, except you need to choose Add New User Defined Type instead of Add Enum Type, and there’s some additional specification on the custom type (though I think the defaults are correct for enums). See http://www.mindscape.co.nz/forums/Post.aspx?ThreadID=2841&PostID=8894 for details.

  • Doesn’t NHibernate map enums as a string by default? Unless you create a UserConvention for it.

  • If I’m reading http://nhforge.org/doc/nh/en/index.html#mapping-declaration-property correctly, the default is to map the enum as the DbType for the underlying type of the enum (usually Int32). This was certainly my experience when I was testing it out. It’s possible this varies between different versions of NHibernate though — I only tested using 2.1.

  • Ahh, I think it was previously a bug, i tried to dig up what i read on stackoverflow but can’t find the original question or the google thread about it.

    At the time I was using 2.0 and it would map any underlying type to a string so it would try store the name instead of the value.

  • Leave a Reply

Archives

Join our mailer

You should join our newsletter! Sent monthly:

Back to Top