枚举解析似乎不适用于 Fluent NHibernate

问题描述 投票:0回答:3

我有一个数据访问类,带有一个名为 Salutation 的枚举:

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

我正在使用 NHibernate 保留该类,直到今天早上我还在使用 .hbm.xml 文件进行映射。但是,我现在已改用 Fluent NHibernate,但加载该类的实例失败(例如):

[HibernateException:无法将 5 解析为称呼]

如您所见,5 应该可以解析为 Salutation(假设 5 是一个 int,则无法从错误消息中看出)。

有人知道这是怎么回事吗?

谢谢

大卫

nhibernate fluent-nhibernate enums nhibernate-mapping
3个回答
35
投票

这比我想象的要容易得多。

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

1
投票

另一个选项是使用 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
    }
}

要使用此枚举约定:

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

在映射文件中,

Map(x => x.SomeEnumField);

0
投票

由于最受接受的答案仍然失败并出现相同的错误,这里是我的解决方案:

public class ConventionName : IUserTypeConvention
{
    public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
    {
        criteria.Expect(property => property.Type == typeof(FluentNHibernate.Mapping.GenericEnumMapper<EnumNameHere>));
    }

    public void Apply(IPropertyInstance instance)
    {
        instance.CustomType<EnumNameHere>();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.