NHibernate自定义集合类型

NHibernate自定义集合类型,nhibernate,collections,nhibernate-mapping,nhibernate-collections,Nhibernate,Collections,Nhibernate Mapping,Nhibernate Collections,我有一个名为Patient的实体对象,这个实体有一个名为Visits的属性,类型为VisitsCollection visitcollections是IList的子类,但它也向集合添加了一些自定义逻辑(如自动排序、一些验证、通知等) 我需要使用自定义集合类型,因为它会向添加到集合中的实体添加一些数据,并透明地执行一些其他文书工作 现在我想在NHibernate中映射它,所以我创建了: <list name="Visits" lazy="true" fetch="select">

我有一个名为
Patient
的实体对象,这个实体有一个名为
Visits
的属性,类型为
VisitsCollection

visitcollections
IList
的子类,但它也向集合添加了一些自定义逻辑(如自动排序、一些验证、通知等)

需要使用自定义集合类型,因为它会向添加到集合中的实体添加一些数据,并透明地执行一些其他文书工作

现在我想在NHibernate中映射它,所以我创建了:

<list name="Visits" lazy="true" fetch="select">
    <key foreign-key="PatientId" />
    <index column="Timestamp" />
    <one-to-many class="Visit" not-found="ignore"/>
</list>

我得到一个例外:

无法将“NHibernate.Collection.PersistentList”类型的对象强制转换为类型“…VisitCollection”

每当我访问访问访问属性时

我还尝试以这种方式绘制它:

<list name="Visits" lazy="true" fetch="select" collection-type="VisitsCollection">
    <key foreign-key="PatientId" />
    <index column="Timestamp" />
    <one-to-many class="Visit" not-found="ignore"/>
</list>

但我还是得到了一个例外:

自定义类型未实现UserCollectionType:..…VisitCollection

我不想从任何NHibernate类型继承我的
visitCollection
,因为集合类是框架的一部分,我希望它是DAL不可知的(因为它将在许多场景中使用,而不仅仅是在数据库中)

关于如何映射这一点,保留代码的结构,有什么想法吗


提前感谢。

我从不使用自定义集合类型,主要是因为我很懒。NHibernate希望您使用我相信的IUserCollectionType,这需要一些管道

与此相反,我的第一站将是考虑使用扩展方法。但是你写的代码是这样的

或者,您可以将集合映射为组件。这对您的场景来说可能更容易一些


也请检查此项。

我也投票赞成不使用自定义集合。无论如何,您可以通过组件来实现

<component name="Warehouses" class="Core.Domain.Collections.EntitySet`1[Core.Domain.OrgStructure.IWarehouseEntity,Core],Core">
<set name="_internalCollection" table="`WAREHOUSE`" cascade="save-update" access="field" generic="true" lazy="true" >
  <key column="`WarehouseOrgId`" foreign-key="FK_OrgWarehouse" />
  <!--This is used to set the type of the collection items-->
  <one-to-many class="Domain.Model.OrgStructure.WarehouseEntity,Domain"/>
</set>


仅供参考,以下是如何使用
FluentNHibernate

我们是否应该创建自定义集合类型是一个单独的主题

public class PatientOverride : IAutoMappingOverride<Patient>
{
        public void Override(AutoMapping<Patient> mapping)
        {
             mapping.Component(
                x => x.Visits,
                part =>
                {
                    part.HasMany(Reveal.Member<VisitsCollection, IEnumerable<Visit>>("backingFieldName")) // this is the backing field name for collection inside the VisitsCollection class
                    .KeyColumn("PatientId")
                    .Inverse(); // depends on your use case whether you need it or not
                });
        }
}
公共类PatientOverride:IAAutoMappingOverride
{
公共无效替代(自动映射)
{
映射.组件(
x=>x.访问,
部分=>
{
part.HasMany(Reveal.Member(“backingFieldName”)//这是VisitCollection类中集合的备份字段名
.KeyColumn(“PatientId”)
.Inverse();//取决于您的用例是否需要它
});
}
}