热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

Questionsaysitallreally,thedefaultisforittomapasastringbutIneedittomapasanint

Question says it all really, the default is for it to map as a string but I need it to map as an int.

问题说真的,默认是它映射为字符串,但我需要它作为一个int映射。

I'm currently using PersistenceModel for setting my conventions if that makes any difference. Thanks in advance.

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

Update Found that getting onto the latest version of the code from the trunk resolved my woes.

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

7 个解决方案

#1


The way to define this convention changed sometimes ago, it's now :

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

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

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

#2


So, as mentioned, getting the latest version of Fluent NHibernate off the trunk got me to where I needed to be. An example mapping for an enum with the latest code is:

因此,正如所提到的那样,将最新版本的Fluent NHibernate从主干上移开,让我到达了我需要的位置。使用最新代码的枚举的示例映射是:

Map(quote => quote.Status).CustomTypeIs(typeof(QuoteStatus));

The custom type forces it to be handled as an instance of the enum rather than using the GenericEnumMapper.

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

I'm actually considering submitting a patch to be able to change between a enum mapper that persists a string and one that persists an int as that seems like something you should be able to set as a convention.

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


This popped up on my recent activity and things have changed in the newer versions of Fluent NHibernate to make this easier.

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

To make all enums be mapped as integers you can now create a convention like so:

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

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;
    }
}

Then your mapping only has to be:

那么你的映射只需要:

Map(quote => quote.Status);

You add the convention to your Fluent NHibernate mapping like so;

你可以像这样添加Fluent NHibernate映射的约定;

Fluently.Configure(nHibConfig)
    .Mappings(mappingCOnfiguration=>
    {
        mappingConfiguration.FluentMappings
            .ConventionDiscovery.AddFromAssemblyOf();
    })
    ./* other configuration */

#3


Don't forget about nullable enums (like ExampleEnum? ExampleProperty)! They need to be checked separately. This is how it's done with the new FNH style configuration:

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

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

#4


this is how I've mapped a enum property with an int value:

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

Map(x => x.Status).CustomType(typeof(Int32));

works for me!

适合我!

#5


For those using Fluent NHibernate with Automapping (and potentially an IoC container):

对于那些使用Fluent NHibernate和Automapping(以及可能是IoC容器)的人:

The IUserTypeConvention is as @Julien's answer above: https://stackoverflow.com/a/1706462/878612

IUserTypeConvention是@ Julien的答案:https://stackoverflow.com/a/1706462/878612

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

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

The Fluent NHibernate Automapping configuration could be configured like this:

Fluent NHibernate Automapping配置可以像这样配置:

    protected virtual ISessionFactory CreateSessionFactory()
    {
        return Fluently.Configure()
            .Database(SetupDatabase)
            .Mappings(mappingCOnfiguration=>
                {
                    mappingConfiguration.AutoMappings
                        .Add(CreateAutomappings);
                }
            ).BuildSessionFactory();
    }

    protected virtual IPersistenceConfigurer SetupDatabase()
    {
        return MsSqlConfiguration.MsSql2008.UseOuterJoin()
        .ConnectionString(x => 
             x.FromConnectionStringWithKey("AppDatabase")) // In Web.config
        .ShowSql();
    }

    protected static AutoPersistenceModel CreateAutomappings()
    {
        return AutoMap.AssemblyOf(
            new EntityAutomapConfiguration())
            .Conventions.Setup(c =>
                {
                    // Other IUserTypeConvention classes here
                    c.Add();
                });
    }

*Then the CreateSessionFactory can be utilized in an IoC such as Castle Windsor (using a PersistenceFacility and installer) easily. *

*然后,CreateSessionFactory可以轻松地在诸如Castle Windsor之类的IoC中使用(使用PersistenceFacility和安装程序)。 *

    Kernel.Register(
        Component.For()
            .UsingFactoryMethod(() => CreateSessionFactory()),
            Component.For()
            .UsingFactoryMethod(k => k.Resolve().OpenSession())
            .LifestylePerWebRequest() 
    );

#6


You could create an NHibernate IUserType, and specify it using CustomTypeIs() on the property map.

您可以创建NHibernate IUserType,并使用属性映射上的CustomTypeIs ()指定它。

#7


You should keep the values as int / tinyint in your DB Table. For mapping your enum you need to specify mapping correctly. Please see below mapping and enum sample,

您应该在数据库表中将值保留为int / tinyint。要映射枚举,您需要正确指定映射。请参阅下面的映射和枚举示例,

Mapping Class

public class TransactionMap : ClassMap Transaction
{
    public TransactionMap()
    {
        //Other mappings
        .....
        //Mapping for enum
        Map(x => x.Status, "Status").CustomType();

        Table("Transaction");
    }
}

Enum

public enum TransactionStatus
{
   Waiting = 1,
   Processed = 2,
   RolledBack = 3,
   Blocked = 4,
   Refunded = 5,
   AlreadyProcessed = 6,
}

推荐阅读
  • 在Docker中,将主机目录挂载到容器中作为volume使用时,常常会遇到文件权限问题。这是因为容器内外的UID不同所导致的。本文介绍了解决这个问题的方法,包括使用gosu和suexec工具以及在Dockerfile中配置volume的权限。通过这些方法,可以避免在使用Docker时出现无写权限的情况。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 阿,里,云,物,联网,net,core,客户端,czgl,aliiotclient, ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • eclipse学习(第三章:ssh中的Hibernate)——11.Hibernate的缓存(2级缓存,get和load)
    本文介绍了eclipse学习中的第三章内容,主要讲解了ssh中的Hibernate的缓存,包括2级缓存和get方法、load方法的区别。文章还涉及了项目实践和相关知识点的讲解。 ... [详细]
  • 本文介绍了Android 7的学习笔记总结,包括最新的移动架构视频、大厂安卓面试真题和项目实战源码讲义。同时还分享了开源的完整内容,并提醒读者在使用FileProvider适配时要注意不同模块的AndroidManfiest.xml中配置的xml文件名必须不同,否则会出现问题。 ... [详细]
  • IjustinheritedsomewebpageswhichusesMooTools.IneverusedMooTools.NowIneedtoaddsomef ... [详细]
  • 使用nodejs爬取b站番剧数据,计算最佳追番推荐
    本文介绍了如何使用nodejs爬取b站番剧数据,并通过计算得出最佳追番推荐。通过调用相关接口获取番剧数据和评分数据,以及使用相应的算法进行计算。该方法可以帮助用户找到适合自己的番剧进行观看。 ... [详细]
  • 使用Ubuntu中的Python获取浏览器历史记录原文: ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • HDFS2.x新特性
    一、集群间数据拷贝scp实现两个远程主机之间的文件复制scp-rhello.txtroothadoop103:useratguiguhello.txt推pushscp-rr ... [详细]
  • Java学习笔记之面向对象编程(OOP)
    本文介绍了Java学习笔记中的面向对象编程(OOP)内容,包括OOP的三大特性(封装、继承、多态)和五大原则(单一职责原则、开放封闭原则、里式替换原则、依赖倒置原则)。通过学习OOP,可以提高代码复用性、拓展性和安全性。 ... [详细]
  • Go Cobra命令行工具入门教程
    本文介绍了Go语言实现的命令行工具Cobra的基本概念、安装方法和入门实践。Cobra被广泛应用于各种项目中,如Kubernetes、Hugo和Github CLI等。通过使用Cobra,我们可以快速创建命令行工具,适用于写测试脚本和各种服务的Admin CLI。文章还通过一个简单的demo演示了Cobra的使用方法。 ... [详细]
  • MyBatis多表查询与动态SQL使用
    本文介绍了MyBatis多表查询与动态SQL的使用方法,包括一对一查询和一对多查询。同时还介绍了动态SQL的使用,包括if标签、trim标签、where标签、set标签和foreach标签的用法。文章还提供了相关的配置信息和示例代码。 ... [详细]
author-avatar
C1_VISION
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有