2009-10-15 96 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)類型。