开发者

Enum parsing doesn't seem to work with Fluent NHibernate

开发者 https://www.devze.com 2023-01-08 02:37 出处:网络
I have a data access class with an Enum called Salutation: public enum Salutation { Unknown = 0, Dame = 1,

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 t开发者_高级运维he 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


This is much easier than I thought.

Map(x => x.WhateverThePropertyNameIs).CustomType(typeof(MyEnumeration));


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号