tags:

views:

47

answers:

2

What's the recommended way to store enums with NHibernate?

To put it another way, should I use the Enum type in the property of the model? it's ID (int)? Or a string?

I would like to know from a Fluent NHibernate perspective.

+2  A: 

The most regular case is to store them just as numeric value. You don't need anything special to do, just map the property.

Some prefer to store it as string (the name of the value as defined in C#). There is a user type which does this. See this blog. I think, the GenericEnumMapper is now part of NH.

There is a frequent question how the enum values can be stored in its own table to define a foreign key to it. There is nothing like this in NH out of the box. IMHO, there is not need to store value to the database which are actually already defined (hard coded constants) in your code.

Stefan Steinegger
Thank you. Would you be able to give me more info on the user type you mention?
UpTheCreek
+2  A: 

We had to deal with this at work recently.

We are using FluentNhibernate and we created a convention for this:

public class EnumConvention : IPropertyConvention, IConventionAcceptance<IPropertyInspector>
{
    public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
    {
        criteria.Expect(x => x.Property.PropertyType.IsEnum);
    }

    public void Apply(IPropertyInstance instance)
    {
        instance.CustomType(instance.Property.PropertyType);
    }
}

Then you can just map your property

Map(x => x.Enum);

In the database, the field is an integer

couellet
Interesting. I guess you have to be careful when adding new members to the enum? (regarding id synch issues)
UpTheCreek
Just make sure to specify manually your enum values and you should not have problems...
couellet