如何使用流畅的NHibernate将枚举映射为int值?

Gar*_*ler 87 nhibernate fluent-nhibernate

问题说真的,默认是它映射为a string但我需要它映射为int.

我目前正在使用PersistenceModel我的约定,如果这有任何区别.提前致谢.

更新 发现从主干上获取最新版本的代码解决了我的困境.

Jul*_*ien 83

定义此约定的方式有时会改变,现在是:

public class EnumConvention : IUserTypeConvention
{
    public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
    {
        criteria.Expect(x => x.Property.PropertyType.IsEnum);
    }

    public void Apply(IPropertyInstance target)
    {
        target.CustomType(target.Property.PropertyType);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是最新版本的流利nhibernate的正确答案 (4认同)
  • 请参阅下面@SztupY的答案,将其扩展为允许可以为空的枚举.http://stackoverflow.com/questions/439003/how-do-you-map-an-enum-as-an-int-value-with-fluent-nhibernate/2716236#2716236 (4认同)

Gar*_*ler 45

因此,如上所述,从主干上获取最新版本的Fluent NHibernate让我到达了我需要的位置.使用最新代码的枚举的示例映射是:

Map(quote => quote.Status).CustomTypeIs(typeof(QuoteStatus));
Run Code Online (Sandbox Code Playgroud)

自定义类型强制将其作为枚举的实例处理,而不是使用GenericEnumMapper<TEnum>.

我实际上正在考虑提交一个补丁,以便能够在持久化字符串的枚举映射器和持久化int的映射器之间进行更改,因为这似乎是您应该能够设置为约定的东西.


这突然出现在我最近的活动中,并且在较新版本的Fluent NHibernate中发生了变化,以使这更容易.

要将所有枚举映射为整数,您现在可以创建如下的约定:

public class EnumConvention : IUserTypeConvention
{
    public bool Accept(IProperty target)
    {
        return target.PropertyType.IsEnum;
    }

    public void Apply(IProperty target)
    {
        target.CustomTypeIs(target.PropertyType);
    }

    public bool Accept(Type type)
    {
        return type.IsEnum;
    }
}
Run Code Online (Sandbox Code Playgroud)

那么你的映射只需要:

Map(quote => quote.Status);
Run Code Online (Sandbox Code Playgroud)

您可以像Froc NHibernate映射一样添加约定;

Fluently.Configure(nHibConfig)
    .Mappings(mappingConfiguration =>
    {
        mappingConfiguration.FluentMappings
            .ConventionDiscovery.AddFromAssemblyOf<EnumConvention>();
    })
    ./* other configuration */
Run Code Online (Sandbox Code Playgroud)

  • 可能是已存在字符串值的旧数据库 (4认同)
  • +1 hainesy.@ Andrew Bullock:回答你的问题:任何处理现实世界数据库的人. (4认同)
  • 以"int mode"作为默认值.谁坚持枚举作为字符串?! (3认同)

Szt*_*upY 40

不要忘记可以为空的枚举(如ExampleEnum? ExampleProperty)!它们需要单独检查.这就是新FNH样式配置的完成方式:

public class EnumConvention : IUserTypeConvention
{
    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)
            );
    }

    public void Apply(IPropertyInstance target)
    {
        target.CustomType(target.Property.PropertyType);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • +1这个添加!第一个版本不适用于可空的枚举(它们仍然是字符串). (4认同)

小智 25

这就是我用int值映射枚举属性的方法:

Map(x => x.Status).CustomType(typeof(Int32));
Run Code Online (Sandbox Code Playgroud)

适合我!

  • 感谢您提供最简单的答案 (2认同)