UpTheCreek
UpTheCreek

Reputation: 32401

Enums with NHibernate

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.

Upvotes: 3

Views: 466

Answers (2)

Stefan Steinegger
Stefan Steinegger

Reputation: 64658

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.

Upvotes: 2

Charles Ouellet
Charles Ouellet

Reputation: 6508

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

Upvotes: 4

Related Questions