Luis,
I couldn't get your suggestion working. Here's what I ended up doing
to have ints in the DB to represent the enum values and avoiding a
flush of the object after it's loaded from the DB.
1) Create the enum type; e.g.,
public class CoreEnums
{
public enum NotificationPriorityType
{
Null = 0,
High = 1,
Medium = 2,
Low = 3
}
}
2) Add a foreign key called e.g., NotificationPriorityTypeFk, to the
table you're mapping to the notification priority types table. The
types table would have one row for each enum value; e.g. 1/High, 2/
Medium, 3/Low
3) Create an NHibernate type which inherits from PersistentEnumType
for the enum type that we want to map; e.g.:
public class NotificationLevelType : PersistentEnumType
{
public NotificationLevelType()
: base(typeof(CoreEnums.NotificationLevelType)) { }
}
4) Override the respective mapping; e.g.:
mapping.Map(notification => notification.MessageLevel,
"NotificationPriorityTypeFk")
.SetAttribute("type", typeof
(NotificationLevelType).AssemblyQualifiedName);
Let me know if you're able to provide a simpler approach to mapping an
enum to an int column without having the loaded object get updated
during flush.
Thanks!
Billy
> > > If you're storing theenumvalues in the Contact table as ints with a
> > > foreign key to a reference table, which I see as an ideal way to do
> > so
> > > in a normalized way, then you'd simply change your map as follows:
>
> > > ct.Map(x => x.Type, "ContactType").Not.Nullable
> > > ().CustomTypeIs(typeof(int));
>
> > > Note that it gets mapped as a type of int, not theenumtype itself.
>
> > > You can get some pretty powerful behavior forenummappings. For
> > > instance, the following example illustrates that the parent object
> > has
> > > a many to many relationship with anenumvalue stored within a many-
> > to-
> > > many table. Note that the many-to-many stores the id to the parent
> > as
> > > well as a normalized id to theenumvalue which is stored in a
> > > reference table:
>
> > > public void Override(AutoMap<Notification> mapping) {
> > > mapping.HasMany<CoreEnums.ChannelType>(x => x.Channels)
> > > .WithTableName("Notification_Channels")
> > > .WithKeyColumn("NotificationFk")
> > > .AsElement("ChannelTypeFk")
> > > .AsBag();
> > > }
>
> > > As long as you properly normalize the database and store theenum
> > > values as ints (with foreign keys to a reference table) instead of
> > > strings, it's very easy to push/pull the info with NHibernate
> > > mappings.
>
> > > Let me know if this doesn't assist.
>
> > > Thanks,
> > > Billy
>
> > > On Feb 20, 5:46 am, Simone Busoli <
simone.bus...@gmail.com> wrote:
>
> > > > Neo, there are a zillion blog posts about how to map enums with
> > NHibernate,
> > > > why don't you try that
> > first?
http://www.google.com/search?q=nhibernate+enum
>
> > > > On Fri, Feb 20, 2009 at 1:37 PM, Neo <
digaomat...@gmail.com> wrote:
>
> > > > > Did anybody have problems to map anenumto a int DB column?