Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum parsing doesn't seem to work with Fluent NHibernate

I have a data access class with an Enum called Salutation:

 public enum Salutation
  {
    Unknown = 0,
    Dame = 1,
    etc
    Mr = 5,
    etc
  }

I am peristing the class with NHibernate, and up until this morning I was using .hbm.xml files for mapping. However, I've now switched to using Fluent NHibernate, but loading instances of the class fails with (for example):

[HibernateException: Can't Parse 5 as Salutation]

As you can see, 5 should be parseable as a Salutation (assuming 5 is an int, it's not possible to tell from the error message).

Anyone know what's going on here?

Thanks

David

like image 700
David Avatar asked Jul 16 '10 10:07

David


2 Answers

This is much easier than I thought.

Map(x => x.WhateverThePropertyNameIs).CustomType(typeof(MyEnumeration));
like image 72
David Avatar answered Oct 19 '22 21:10

David


Another option is using, EnumConvention:

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestApp
{
    using FluentNHibernate.Conventions;
    using FluentNHibernate.Conventions.AcceptanceCriteria;
    using FluentNHibernate.Conventions.Inspections;
    using FluentNHibernate.Conventions.Instances;

    public class EnumConvention :
        IPropertyConvention,
        IPropertyConventionAcceptance
    {
        #region IPropertyConvention Members

        public void Apply(IPropertyInstance instance)
        {
            instance.CustomType(instance.Property.PropertyType);
        }

        #endregion

        #region IPropertyConventionAcceptance Members

        public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
        {
            criteria.Expect(x => x.Property.PropertyType.IsEnum ||
            (x.Property.PropertyType.IsGenericType &&
             x.Property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) &&
             x.Property.PropertyType.GetGenericArguments()[0].IsEnum)
            );
        }

        #endregion
    }
}

To use this enumconvention:

...
var fluentCfg = Fluently.Configure().Database(cfg).Mappings(
                    m => m.FluentMappings.AddFromAssemblyOf<SomeObjectMap>().Conventions.Add<EnumConvention>());
...

And in mapping file,

Map(x => x.SomeEnumField);
like image 26
iknowitwasyoufredo Avatar answered Oct 19 '22 19:10

iknowitwasyoufredo