【问题标题】:Using an IUsertype with an ID field in NHibernate 3.3+ Mapping-By-Code在 NHibernate 3.3+ Mapping-By-Code 中使用带有 ID 字段的 IUsertype
【发布时间】:2016-12-06 18:09:46
【问题描述】:

我正在使用 NHibernate 3.3 并使用 ma​​pping-by-code 系统。我正在使用的表/数据库将为我的应用程序只读

我面临的问题是我的主键列在 SQL Server 中存储为二进制字段。我需要将其读取为字符串,不幸的是我无法修改表(包括添加索引视图)。

此时,我正在尝试使用 IUsertype 将值从二进制转换为字符串。 但是,在尝试将实体中 Id 列的类型设置为使用 IUserType 时,我遇到了困难。

我已经成功地为以下示例的普通属性执行此操作,但无法弄清楚如何为 ID 列和外键列执行此操作。

public class ExampleEntity
{
    public virtual String MyIdColumn { get; set; }
    public virtual Country Country { get; set; }
}


public class ExampleEntityMap : ClassMapping<ExampleEntity>
{

    public ExampleEntityMap()
    {
        Table("Table");

        Id(i => i.Id, map =>
        {
            map.Column("MyIdColumn");
            map.Type(???);
        });
        Property(i => i.Country, map =>
                                  {
                                      map.Column("Country");
                                      map.Type<CountryEnumUserType>();
                                  });
    }
}
  1. NH3.3 Mapping By Code 是否可行?
  2. 我必须实现 IIdentifierType 来实现 IUserType 对 Id 字段的作用吗?
  3. NHibernate 转换器可以实现我正在做的事情吗?
  4. 还有其他方法可以解决这个问题吗?除了检索数据并在 C# 中进行转换之外,因为我必须对十几个表中的许多列执行此操作。

谢谢

【问题讨论】:

    标签: c# nhibernate fluent-nhibernate nhibernate-mapping nhibernate-mapping-by-code


    【解决方案1】:

    想通了。我最终使用 ComposedId 属性来映射 Id 列,它允许您为 Id 列指定 IUserType。

    public class ExampleEntityMap : ClassMapping<ExampleEntity>
    {
        public ExampleEntityMap()
        {
            Table("Table");
    
            ComposedId(i => i.Property(p => p.MyIdColumn, map =>
                                                        {
                                                            map.Column("MyIdColumn");
                                                            map.Type<MyIdColumnUserType>();
                                                        }));
    
            Property(i => i.Country, map =>
                                  {
                                      map.Column("Country");
                                      map.Type<CountryEnumUserType>();
                                  });
        }
    }
    

    【讨论】:

      【解决方案2】:

      你提到的解决方案虽然有点破解。

      要使其正常工作,实体还需要覆盖 Equality / GetHashCode,如下所示:

          public override bool Equals(object obj)
          {
              return Country == (obj as ExampleEntity)?.Country;
          }
      
          public override int GetHashCode()
          {
              return this.Country.GetHashCode();
          }
      

      当使用Get 加载时需要使用:

      session.Get(new ExampleEntity{ Country = Countries.Kenya });
      

      我会尝试找出更好的解决方案并在此处发布。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-02
        • 2014-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多