How to persist an enum using NHibernate

Meidan Alon picture Meidan Alon · Nov 2, 2008 · Viewed 32.2k times · Source

Is there a way to persist an enum to the DB using NHibernate? That is have a table of both the code and the name of each value in the enum.

I want to keep the enum without an entity, but still have a foreign key (the int representation of the enum) from all other referencing entities to the enum's table.

Answer

Emad picture Emad · Dec 15, 2009

Why are you guys over complicating this? It is really simple.

The mapping looks like this:

<property name="OrganizationType"></property>

The model property looks like this:

public virtual OrganizationTypes OrganizationType { get; set; }

The Enum looks like this:

public enum OrganizationTypes
{
    NonProfit = 1,
    ForProfit = 2
}

NHibernate will automatically figure it all out. Why type more than you need????