【问题标题】:How to map a nullable enum to an integer in NHibernate?如何将可为空的枚举映射到 NHibernate 中的整数?
【发布时间】:2021-10-26 23:06:50
【问题描述】:

我有一个enum(它的值是位标志)如下:

[Flags]
public enum ItemType
{
    InventoryPart = 0x1,
    Service = 0x2,
    Discount = 0x4,
    NonInventory = 0x8,
    MiscellaneousCharge = 0x10,
    InventoryAssembly = 0x20,
    DescriptionLine = 0x40,
    All = InventoryPart | Service | Discount | NonInventory | MiscellaneousCharge | InventoryAssembly | DescriptionLine,
}

然后我有一个实体(Item),上面有一个属性(注意:ItemTypenullable):

 private ItemType? _itemType;
 public ItemType? ItemType { get { return _itemType; } set { _itemType = value; } }

我在hbm.xml 文件中按如下方式映射此属性:

<property name="ItemType" type="Int32" column="ItemType" not-null="false" />

在数据库中,该字段是一个整数(允许为空)。

当我运行代码时,我从 NHibernate 库中得到一个异常:

无效的演员表(检查您的映射是否有属性类型不匹配);二传手 PrlSystems.AccountingLibrary.Model.Item

注意: 当此属性 (Item.ItemType) 之前不是 nullable 时,一切正常,使此属性 nullable 导致上述异常。此外,对于像ints、DateTimes、nullable 这样的内置类型,这些类型的类属性可以直接映射到它们的具体类型:intDateTime

我试过这样映射,但还是不行:

System.Nullable`1[[System.Int32]] 

现在正确的 NHibernate 映射应该是什么?

【问题讨论】:

    标签: c# .net nhibernate nhibernate-mapping hbmxml


    【解决方案1】:

    好的,在更详细地研究了这个问题之后,这个问题的主要原因是:

    您不能将 Enum 值转换为 (int?),只能将其转换为 (int)。

    为了解决这个问题,我通过实现 IUserType 接口编写了一个自定义枚举映射器。在那里,我处理可空枚举显式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      相关资源
      最近更新 更多