100% of people found this useful
Sometimes you'd want to map an Enum field to the DB. The default behaviour of NHibernate is to persist the Enum value ToString()'s output to the DB. But at times you'd rather persist a custom value for each enum value. Popular example will be:
namespace Model
{
public enum SexType
{
Male,
Female
}
}
The values "Female" or "Male" will be persisted to the DB should you use a property of type SexType, but your DBA wants you to persist "F" for female and "M" for male.
There's DescriptionAttribute in System.ComponentModel that can be used to describe the enum values:
using System.ComponentModel;
namespace Model
{
public enum SexType
{
[Description("M")]
Male,
[Description("F")]
Female
}
}
What we need now is:
- A way to extract the description for a given value,
- A way to get a value out of a description,
- and a custom IUserType that will know how to apply 1. and 2.
Luckily enough, these things are already implemented in the new D9 project
- Get the D9 project binaries.
- Reference D9.Commons in your application and make sure you initialise the enums. You do that by calling Enums.Initialise(typeof(SexType)) at application initialisation time.
- Map the enum using the generic IUserType implementation D9.NHibernate.UserTypes.DescribedEnumStringType
Example:
<property
name = "Sex"
column = "Sex"
type = "D9.NHibernate.UserTypes.DescribedEnumStringType`1Model.SexType, Model,
D9.NHibernate" />
or if you use Castle ActiveRecord attributes for mapping:
[Property(ColumnType = "D9.NHibernate.UserTypes.DescribedEnumStringType`1Model.SexType, Model, D9.NHibernate")
The source code for the Enums and DescribedEnumStringType classes is available under New BSD license in the D9 project source repository
You can read more on D9, at http://www.kenegozi.com/Blog/Tag/d9.aspx