在 NHibernate 3.3+ Mapping-By-Code 中使用带有 ID 字段的 IUsertype
本文关键字:ID 字段 IUsertype NHibernate Mapping-By-Code | 更新日期: 2023-09-27 18:32:54
我正在使用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 按代码映射是否可能?
- 我是否必须实现 IIdentifierType 来实现 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 });
我将尝试找出更好的解决方案并将其发布在这里。