Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping to an Enum bit flag in Nhibernate

Tags:

c#

nhibernate

Take the following Enum Flag

[Flags]
enum Permssions
{
   CanComment = 1,
   CanEdit = 2,
   CanDelete = 4,
   CanRemoveUsers = 8,
   All = CanComment | CanEdit | CanDelete | CanRemoveUsers 
}

In NHibernate I have mapped to a enum before using:

<property type="n.Permssions, n.Permssions"
name="Permssions" column="Permssions"></property>

My question is, how do I map a bitwise field to a Flag field using NHibnerate?

like image 731
Ted Smith Avatar asked Mar 23 '09 10:03

Ted Smith


1 Answers

When I map an enum, and this enum has a backing value of type 'int', I just map my enum property to an int field in the database. I haven't run into problems for this.
I have done this for flag enums as well, and this just works without problems. When you combine certain flags, NHibernate will persist the 'combination' of those flags into the specified column in the database.
When you retrieve the instance that has a property of 'flag enums', then NHibernate will reconstitute it back to the correct combination.
For instance, if the DB contains '3', then NHibernate will populate your property with the combination of the apropriate values.
In fact, I let NHibernate figure it out all by himself:

<property name="OnCallType" column="OnCallType" />

where the OnCallType column is of type int in my DB, and the OnCallType property is an enumerated type that has the flags attribute.

like image 126
Frederik Gheysels Avatar answered Sep 19 '22 05:09

Frederik Gheysels