1

我正在使用NHibernate 3.3并使用映射代码系统。我正在使用的表/数据库将为我的应用程序只读在NHibernate中使用带ID字段的IUsertype 3.3+映射代码

我面临的问题是我的主键列存储为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映射到代码?
  2. 我必须实现一个IIdentifierType而不是实现IUserType为Id字段做什么?
  3. NHibernate变压器可以实现我在做什么?
  4. 有没有解决这个问题的另一种方法?除了检索数据并在C#中进行转换之外,我必须为十几个表中的许多列执行此操作。

感谢

回答

0

想通了。我最终使用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>(); 
           }); 
    } 
} 
0

您提到的解决方案的工作原理虽然有些瑕疵。

对于它的工作的实体也需要重写平等/ GetHashCode的,东西就行:

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

我:

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

    public override int GetHashCode() 
    { 
     return this.Country.GetHashCode(); 
    } 

而且使用Get需要加载时,使用完成将尝试找出更好的解决方案并将其发布到此处。

相关问题