Search This Blog

15 February 2010

Nhibernate and mapping Enums

When using NHibernate one has to be careful in certain circumstances to avoid small errors that may have a huge impact. In one area an "error" might be hidden for a long time without anybody noticing it and everything working as it should. 

As soon as you create a mapping file with properties that are explicitly given types your should be aware what you are doing. If you for instance create a mapping file where you map a bit column and specify that the type for this column is Int32 and then in the mapping class define this property as an Enum you might be getting into problems. 

Since the class that is used for the mapping in the project might differ from the actual values in the database NHibernate will have problems understanding that nothing really has changed.

For example if you have the following in your mapping file, maybe for mapping up a user and specify gender for the user.
<property name="Gender" not-null="true" type="Int32" />

And the following class defined: 

public class Person
{
     public enum GenderEnum
     {
        Male = 0,
        Female
     }
     public GenderEnum Gender;
}

Once you load this element into memory the property Gender will be tranformed from being an Int32 value in the database to a GenderEnum type in the project. Later on when you either want to unload this object or load another object of the same type or any operation on the object that might trigger an update event for NHibernate such an event will indead be triggered, regardless if you have changed any values or not. The reason for this is that NHibernate detects a change of in the object, the property that is mappped as being Int32 in the database is now returned as an Enum. 

To fix this problem remove the type declaration in the mapping file and let NHibernate resolve the type itself.

A more extensive information about this problem can be found in the following links:

No comments:

Post a Comment