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开发者_如何学C property of the model? it's ID (int)? Or a string?
I would like to know from a Fluent NHibernate perspective.
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
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.
精彩评论