bfabry
bfabry

Reputation: 1904

Mapping a collection of enums with NHibernate

Mapping a collection of enums with NHibernate

Specifically, using Attributes for the mappings.

Currently I have this working mapping the collection as type Int32 and NH seems to take care of it, but it's not exactly ideal.

The error I receive is "Unable to determine type" when trying to map the collection as of the type of the enum I am trying to map.

I found a post that said to define a class as

public class CEnumType : EnumStringType {
  public CEnumType() : base(MyEnum) { }
}

and then map the enum as CEnumType, but this gives "CEnumType is not mapped" or something similar.

So has anyone got experience doing this?

So anyway, just a simple reference code snippet to give an example with

    [NHibernate.Mapping.Attributes.Class(Table = "OurClass")]
    public class CClass : CBaseObject
    {
        public enum EAction
        {
            do_action,
            do_other_action
        };

        private IList<EAction> m_class_actions = new List<EAction>();

        [NHibernate.Mapping.Attributes.Bag(0, Table = "ClassActions", Cascade="all", Fetch = CollectionFetchMode.Select, Lazy = false)]
        [NHibernate.Mapping.Attributes.Key(1, Column = "Class_ID")]
        [NHibernate.Mapping.Attributes.Element(2, Column = "EAction", Type = "Int32")]
        public virtual IList<EAction> Actions
        {
            get { return m_class_actions; }
            set { m_class_actions = value;}
        }
}

So, anyone got the correct attributes for me to map this collection of enums as actual enums? It would be really nice if they were stored in the db as strings instead of ints too but it's not completely necessary.

Upvotes: 1

Views: 3377

Answers (4)

Lisa
Lisa

Reputation: 4400

You will need to map your CEnum type directly. In XML mappings this would mean creating a new class mapping element in your NHibernate XML mappings file.

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="YourAssembly"
   auto-import="true" default-lazy="false">

   ...

   <class name="YourAssemblyNamespace.CEnum" table="CEnumTable" mutable="false" >
      <id name="Id" unsaved-value="0" column="id">
         <generator class="native"/>
      </id>

      ...

   </class>

</hibernate-mapping>

To do it with attribute mappings, something like this on top of your CEnum class:

[NHibernate.Mapping.Attributes.Class(Table = "CEnumTable")] //etc as you require

Upvotes: 2

Geoff Bennett
Geoff Bennett

Reputation: 2553

While I haven't tried using it myself, I stumbled across this code a little while ago and it looks pretty interesting:

http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/08/12/enumeration-classes.aspx

Like I said, I haven't used it myself, but I'm going to give it a go in a project RSN.

Upvotes: 1

kͩeͣmͮpͥ ͩ
kͩeͣmͮpͥ ͩ

Reputation: 7846

instead of

[NHibernate.Mapping.Attributes.Element(2, Column = "EAction", Type = "Int32")]

try

[NHibernate.Mapping.Attributes.Element(2, Column = "EAction", Type = "String")]

ie: change the Int32 to String

Upvotes: 1

alvin
alvin

Reputation: 179

This is the way i do it. There's probably an easier way but this works for me.

Edit: sorry, i overlooked that you want it as a list. I don't know how to do that...

Edit2: maybe you can map it as a protected IList[string], and convert to public IList[EAction] just as i do with a simple property.

    public virtual ContractGroups Group
    {
        get
        {
            if (GroupString.IsNullOrEmpty())
                return ContractGroups.Default;

            return GroupString.ToEnum<ContractGroups>(); // extension method
        }
        set { GroupString = value.ToString(); }
    }

    // this is castle activerecord, you can map this property in NH mapping file as an ordinary string
    [Property("`Group`", NotNull = true)] 
    protected virtual string GroupString
    {
        get;
        set;
    }



    /// <summary>
    /// Converts to an enum of type <typeparamref name="TEnum"/>.
    /// </summary>
    /// <typeparam name="TEnum">The type of the enum.</typeparam>
    /// <param name="self">The self.</param>
    /// <returns></returns>
    /// <remarks>From <see href="http://www.mono-project.com/Rocks">Mono Rocks</see>.</remarks>
    public static TEnum ToEnum<TEnum>(this string self)
        where TEnum : struct, IComparable, IFormattable, IConvertible
    {
        Argument.SelfNotNull(self);

        return (TEnum)Enum.Parse(typeof(TEnum), self);
    }

Upvotes: 1

Related Questions