简体   繁体   English

如何使用NHibernate映射自定义列表

[英]How to map custom list with NHibernate

I have a class with a custom list which inherits from List and cannot get the NHibernate mapping working. 我有一个带有自定义列表的类,该类从List继承而来,无法使NHibernate映射正常工作。

public class MyClass
{
  private MyList<Foo> foos;

  public virtual MyList<Foo> Foos
  {
      get { return foos; }
      set { foos= value; }
  }
}

<bag name="Foos" access="property" cascade="all-delete-orphan" batch-size="5">
      <key column="MyClassId"/>
      <one-to-many class="Domain.Model.MyClass, Domain"/>
</bag>

I got the exception 我有例外

Unable to cast object of type 'NHibernate.Collection.Generic.PersistentGenericBag 1[Domain.Model.Foo]' to type 'Domain.Model.MyList 1[Domain.Model.Foo]'. 无法将类型为“ NHibernate.Collection.Generic.PersistentGenericBag 1[Domain.Model.Foo]' to type 'Domain.Model.MyList对象1[Domain.Model.Foo]' to type 'Domain.Model.MyList 1 [Domain.Model.Foo]”类型。

Following this blog , I tried to wrap the bag in a component, 在这篇博客之后 ,我尝试将袋子包装成一个组件,

<component name="Foos" access="nosetter.camelcase-underscore">
  <bag name="Foos" access="property" cascade="all-delete-orphan" batch-size="5">
      <key column="MyClassId"/>
      <one-to-many class="Domain.Model.MyClass, Domain"/>
  </bag>
</component>

resulting in the error 导致错误

Could not find a getter for property 'Foos' in class 'Domain.Model.MyList`1[Domain.Model.Foo]' 在类“ Domain.Model.MyList`1 [Domain.Model.Foo]”中找不到属性“ Foos”的吸气剂

MyList has only a method to add objects. MyList只有一种添加对象的方法。

public class MyList<T> : List<T>
{
    public new void Add(T item)
    {
        //custom stuff

        base.Add(item);
    }
}

If MyList<T> is a concrete type (and if I remember correctly) NHibernate will complain with an exception similar to (or same as?) the one your getting. 如果 MyList<T>是一个具体类型(如果我没记错的话),NHibernate将抱怨与您得到的异常类似(或相同?)的异常。

That could the be solved by using IList<T> instead. 可以通过使用IList<T>来解决。

This should work... 这应该工作...

public class MyClass
{
    public virtual IList<Foo> Foos { get; private set; }

    public MyClass()
    {
        Foos = new MyList<Foo>();
    }
}

Changed the mapped property to an IList and set it to MyList 将映射的属性更改为IList并将其设置为MyList

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM