【问题标题】:Using string enums in NHibernate - GetValue never gets fired在 NHibernate 中使用字符串枚举 - GetValue 永远不会被解雇
【发布时间】:2012-06-06 07:33:33
【问题描述】:

在我的 NHibernate 驱动的应用程序中,我有一些类的某些属性不是完整的实体。即,我有一个客户类 客户类型属性。为客户类型属性创建一个单独的类似乎是一种资源浪费。 我要做的是使用代码映射将客户类型映射到 NHibernate 3.2 中的枚举字符串。在 StackOverflow 上搜索, 我找到了一个可能的解决方案,代码如下:

   public class Customer
    {
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
        public virtual CustomerType CustomerType { get; set; }
    }

    public class CustomerMap : ClassMapping<Customer>
    {

        public CustomerMap()
        {
            Id(x => x.Id);
            Property(x => x.Name, m => m.Length(100));
            Property(x => x.CustomerType, m =>
                     {
                         m.Column("CustomerTypeId");
                         m.Type(typeof (CustomerTypeMap), null);
                     });

        }
    }

    public enum CustomerType
    {
        Big_Customer,
        Small_Customer
    }

    public class CustomerTypeMap : EnumStringType<CustomerType>       
    {
        public override object GetValue(object code)
        {
            return code == null
                    ? string.Empty
                    : code.ToString().Replace('_', ' ');
        }

        public override object GetInstance(object code)
        {

            var str = (string)code;

            if (string.IsNullOrEmpty(str)) return StringToObject(str);
            else return StringToObject(str.Replace(" ", "_"));
        }
    }

此解决方案仅部分有效。正如您从代码中看到的那样,我试图通过替换下划线来使枚举字符串看起来不错,以便获得“大客户”而不是“大客户”。这行不通。将换行符放入代码中,我注意到被覆盖的 GetInstance 函数被调用,但 GetValue 函数从未被触发。任何帮助将不胜感激。

【问题讨论】:

  • 为什么首先要下划线?命名枚举成员的“.Netty”方式是 BigCustomer 和 SmallCustomer。
  • @Oskar - 我认为这从代码中很明显。我想要一个不错的输出,所以 BigCustomer 是不可能的。最简单的方法似乎是用空格代替下划线。

标签: c# nhibernate orm


【解决方案1】:

我同意您不应该为诸如 CustomerType 之类的东西创建新实体。 NHibernate 也不希望您这样做。 Fluent NHibernate 默认将枚举映射为字符串(我假设您使用的是最新版本),但显然您希望拥有更细粒度的控制。

我使用 Fluent NH 已经有一段时间了,但不妨试试这个(除非 API 已更改):

Map(x => x.CustomerType).Column("CustomerTypeId").CustomType<CustomerTypeMap>();

再一次,不确定这是否(仍然)有效,因为 API 发生了变化/变化很大。

【讨论】:

  • 我正在使用 NHibernate 的 3.2 代码映射,我提出的解决方案确实可以部分工作。不起作用的是下划线的替换,因为覆盖的 GetValue() 永远不会被调用。
猜你喜欢
  • 2013-08-21
  • 2016-04-05
  • 1970-01-01
  • 2018-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-13
  • 2021-08-09
相关资源
最近更新 更多