2009-10-15 63 views
1

我刚开始使用NHibernate。我设置一个简单的多对许多使用产品和供应商如下场景: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和列表(T),但我不断收到相应的错误。

无法投类型的对象NHibernate.Collection.Generic.PersistentGenericBag 1[Domain.Supplier]' to type 'System.Collections.Generic.List 1 Domain.Supplier]

缺少什么我在这里?

回答

2

本文档讨论了如何使用IList或IList(实体)创建一个包,并使用List或List(实体)构造它。 (NHibernate 1.2参考的6.2节)。

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

你的集合映射应该然后是(使用泛型 - 以(供应商),以去除仿制药:

'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 
+0

非常感谢完美的作品! – 2009-10-16 16:01:23

0

公共属性Supplier.Products需要是ISetISet(Of Product)类型。