Search code examples
c#.netnhibernatenhibernate-mappinghbmxml

How to map a nullable enum to an integer in NHibernate?


I have an enum (which values are bit flags) as follows:

[Flags]
public enum ItemType
{
    InventoryPart = 0x1,
    Service = 0x2,
    Discount = 0x4,
    NonInventory = 0x8,
    MiscellaneousCharge = 0x10,
    InventoryAssembly = 0x20,
    DescriptionLine = 0x40,
    All = InventoryPart | Service | Discount | NonInventory | MiscellaneousCharge | InventoryAssembly | DescriptionLine,
}

Then I have entity (Item) with a property on it (note: ItemType is nullable):

 private ItemType? _itemType;
 public ItemType? ItemType { get { return _itemType; } set { _itemType = value; } }

I am mapping this property as follows in the hbm.xml file:

<property name="ItemType" type="Int32" column="ItemType" not-null="false" />

In the database, this field is an integer (that allows nulls).

When I run the code, I get an exception from NHibernate library:

Invalid Cast (check your mapping for property type mismatches); setter of PrlSystems.AccountingLibrary.Model.Item

NOTE: When this property (Item.ItemType) was not a nullable before, everything worked, making this property nullable causes the exception mentioned above. Also, for built in types like ints, DateTimes, nullable class properties of these types can be mapped straight to their concrete types: int, DateTime.

I have tried mapping it this way but it still doesn't work:

System.Nullable`1[[System.Int32]] 

What should the correct NHibernate mapping be now?


Solution

  • Okay, after looking at this issue in more detail the main cause of this problem is the fact that:

    You cannot cast an Enum value to an (int?), you can only cast it to (int).

    To resolve this problem, I wrote a custom enum mapper by implementing IUserType interface. In there, I handle nullable enums expliclity.