C# 通过代码在NHibernate 3.3+映射中使用带有ID字段的IUsertype

C# 通过代码在NHibernate 3.3+映射中使用带有ID字段的IUsertype,c#,nhibernate,fluent-nhibernate,nhibernate-mapping,mapping-by-code,C#,Nhibernate,Fluent Nhibernate,Nhibernate Mapping,Mapping By Code,我正在使用NHibernate 3.3并使用代码映射系统。我正在使用的表/数据库对于我的应用程序将是只读的 我面临的问题是,我的主键列在SQL Server中存储为二进制字段。我需要将其作为字符串读取,不幸的是,我无法修改该表,包括添加索引视图 此时,我正在尝试使用IUsertype将值从二进制转换为字符串。 但是,我在尝试将实体中Id列的类型设置为使用IUserType时遇到了问题 我已经成功地对普通属性执行了此操作,如下面的示例所示,但无法确定如何对ID列和外键列执行此操作 public c

我正在使用NHibernate 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>();
                                  });
    }
}
通过代码映射NH3.3是否可以实现这一点? 我必须实现IIIdentifierType来实现IUserType对Id字段的功能吗? NHibernate变压器能实现我所做的吗? 还有别的办法解决这个问题吗?除了检索数据并用C进行转换之外,我还必须对十几个表中的许多列执行此操作。
谢谢

把它弄明白了。最后,我使用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>();
                              });
    }
}

你提到的解决方案虽然有点麻烦,但仍然有效

要使其正常工作,实体还需要覆盖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 });
我将尝试找出一个更好的解决方案,并张贴在这里