【问题标题】:How to map custom list with NHibernate如何使用 NHibernate 映射自定义列表
【发布时间】:2012-06-21 14:53:57
【问题描述】:

我有一个带有自定义列表的类,它继承自 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>

我遇到了异常

无法转换类型为“NHibernate.Collection.Generic.PersistentGenericBag1[Domain.Model.Foo]' to type 'Domain.Model.MyList1[Domain.Model.Foo]”的对象。

按照这个blog,我尝试将包包在一个组件中,

<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>

导致错误

在“Domain.Model.MyList`1[Domain.Model.Foo]”类中找不到属性“Foos”的 getter

MyList 只有一个添加对象的方法。

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

        base.Add(item);
    }
}

【问题讨论】:

  • 你能告诉我们MyList&lt;T&gt;的定义吗?

标签: c# .net nhibernate mapping custom-lists


【解决方案1】:

这应该可以...

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

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

将映射属性更改为IList 并将其设置为MyList

【讨论】:

    【解决方案2】:

    如果 MyList&lt;T&gt; 是一个具体类型(如果我没记错的话)NHibernate 会抱怨一个与你得到的类似(或相同?)的异常。

    这可以通过使用IList&lt;T&gt; 来解决。

    【讨论】:

      猜你喜欢
      • 2011-12-06
      • 1970-01-01
      • 2012-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多