views:

470

answers:

2

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.

A: 

Not sure how to do it properly but here's another workaround:

Add a class called CostContributorEntity. The class will have only property: ID, of type CostContributor. You don't need to create a real table unless you want to.

In the consuming classes change ReplacementContributor to be of type CostContributorEntity, and map it as References(x => x.ReplacementContributor);

Use session.Load(CostContributor.Blahblah1) to create instance of CostContributorEntity you can assign to ReplacementContributor.

zvolkov
+1  A: 

This was a bug and it's been fixed.

Jamie Ide