C# – How to map a nullable enum in NHibernate

cfluent-nhibernatenhibernate

I have been unable to persist a nullable enum using NHibernate with Fluent NHibernate configuration. NHibernate attempts to save a string representation of the enum and I get the error

System.Data.SqlClient.SqlException: Conversion failed when converting the 
nvarchar value 'VGS' to data type tinyint.

The property is defined as

public virtual CostContributor? ReplacementContributor { get; private set; }

and the mapping is

Map(x => x.ReplacementContributor).CustomTypeIs(typeof(CostContributor?));

I've tried every combination of CustomTypeIs and CustomSqlTypeIs, including substituting int? or byte? for CostContributor?, but nothing has worked. It works fine if I make it a non-nullable type.

Is it possible to map a nullable enum in NHibernate? Or is this a bug or unsupported feature in NHibernate?

If I can't make this work I'm going to add an Undefined value to my enum as a workaround.

Best Answer