代码之家  ›  专栏  ›  技术社区  ›  Adam Pope

nHibernate多对多域对象属性

  •  1
  • Adam Pope  · 技术社区  · 16 年前

    我刚开始和NHibernate合作。我使用产品和供应商设置了一个简单的多对多方案,如下所示:

    <class name="Product" table="Products">
        <id name="Id">
          <generator class="guid" />
        </id>
        <property name="Name" />
    
        <bag name="SuppliedBy" table="ProductSuppliers" lazy="true">
          <key column="ProductId" foreign-key="FK_ProductSuppliers_ProductId" />
          <many-to-many column="SupplierId" class="Supplier" />
        </bag>
    </class>
    
    <class name="Supplier" table="Suppliers">
        <id name="Id">
          <generator class="guid" />
        </id>
        <property name="Name" />
    
        <bag name="Products" table="ProductSuppliers" lazy="true" inverse="true">
          <key column="SupplierId"  foreign-key="FK_ProductSuppliers_SupplierId" />
          <many-to-many column="ProductId" class="Product" />
        </bag>
    </class>
    

    我现在正在尝试将包连接到我的域对象。通过阅读我提出的文档(使用iesi.collections lib):

    'In Product
    Private _Suppliers As ISet = New HashedSet()
    Public Overridable Property SuppliedBy() As HashedSet
        Get
            Return _Suppliers
        End Get
        Set(ByVal value As HashedSet)
            _Suppliers = value
        End Set
    End Property
    
    'In Supplier
    Private _Products As ISet = New HashedSet()
    Public Overridable Property Products() As HashedSet
        Get
            Return _Products
        End Get
        Set(ByVal value As HashedSet)
            _Products = value
        End Set
    End Property
    

    但是,当我尝试将供应商添加到产品并调用保存时,我会得到以下错误

    无法将“nhibernate.collection.persistentbag”类型的对象强制转换为“iesi.collections.hashedset”类型

    我尝试过使用各种类型,例如,ICollection和List(of T),但是我一直得到相同的错误。

    无法强制转换“nhibernate.collection.generic.PersistentGenericBag”类型的对象 1[Domain.Supplier]' to type 'System.Collections.Generic.List 1[域供应商]

    我这里缺什么?

    2 回复  |  直到 16 年前
        1
  •  2
  •   Michael Gattuso    16 年前

    文档讨论如何使用ilist或ilist(实体的)创建包,并使用list或list(实体的)构造包。(参考NHIBERNATE 1.2第6.2节)。

    包的语义与集合的语义不匹配,即集合只能有唯一的实例,包可以有重复的实例。作为一个公平的评论,一个列表也不完全匹配一个包的语义(一个包没有索引),但它足够接近NHibernate。

    然后,您的集合映射应该(使用泛型-take(of supplier)删除泛型:

    'In Product
    Private _Suppliers As IList(of Supplier) = New List(of Supplier)
    Public Overridable Property SuppliedBy() As IList(of Supplier)
        Get
            Return _Suppliers
        End Get
        Set(ByVal value As IList(of Supplier))
            _Suppliers = value
        End Set
    End Property
    
        2
  •  0
  •   yfeldblum    16 年前

    公共财产 Supplier.Products 需要是类型 ISet ISet(Of Product) .

    推荐文章