Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent NHibernate mapping nullable enum

I need to map a nullable enum in my class but am getting exceptions.

NHibernate.PropertyAccessException: Invalid Cast (check your mapping for property type mismatches); setter of App.Model.Stock ---> System.InvalidCastException: Specified cast is not valid.

I have narrowed the issue down to one specific property, which I describe below.

This was previously answered here, but the solution links to a page which no longer exists.

Here is my code, which I have reduced to contain only the portions I am concerned with.

public enum eColor
{
    Red,
    Blue
}

public class Stock 
{
    public virtual eColor? Color { get; protected set; }
}

Here is my mapping (stripped down):

public class StockMap : ClassMap<Stock>
{
    Map(x => x.Color).CustomType<int>();
}

I have tried all of the following with the same results:

Map(x => x.Color).CustomType<int>();
Map(x => x.Color).CustomType<int?>();
Map(x => x.Color).CustomType<int>().Nullable();
Map(x => x.Color).CustomType<int?>().Nullable();

This appeared to be a bug a long time ago and there was a workaround. I am using Fluent 1.3.0.0 and NHibernate 3.3.1.4000.

like image 256
bunggo Avatar asked Dec 14 '12 15:12

bunggo


1 Answers

You should specify the enum type in CustomType<T>(), e.g. CustomType<eColor>(). This will give you integers in the database.

like image 162
Oskar Berggren Avatar answered Nov 08 '22 05:11

Oskar Berggren