Reality-Loop

.Net QuickTip: Persisting enums as strings with NHibernate

April 22, 2010 | 1 Minute Read
This post was originally posted on my old blog.

Scenario: You want to map the values of an enum-typed property of an entity as a string into the database with NHibernate.

Solution: NHibernate stores enums with their numeric value into the database as default.
In order to save the value as string, you have to use the type attribute of the property element in the xml-mapping.
As of NHibernate 2.1 you can use the type NHibernate.Type.EnumStringType<T> like this:

<property column="DataProviderConst" name="DataProvider"
   type="EnumStringType`1[[My.Namespace.DataProvider, My.Namespace]]">
(note the strange syntax to declare the generic type)

On the web there are floating a lot of articles around, telling that you have to create a derived Type of NHibernate.Type.EnumStringType for each enum, or generate a generic EnumMapper type.
This is not necessary since NH 2.1. This post finally enlightened me.

In Fluent NHibernate mapping enums to strings is the default. You don't have to do anything.
Now, if mapping enums to strings is a best practice or an antipattern is a whole different question.

http://www.google.com/s2/favicons?domain=twitter.com follow me on twitter, I need some friends :-)