2009-05-05 56 views
4

我有一個Contact(基類),一個叫做Customer的類和一個叫做Supplier的類。客戶和供應商類別均來自Contact。如何在NHibernate中映射集合<T>?

客戶與訂單有0..n的關係。我想要在客戶端擁有一個Collection屬性,並將其映射到NHibernate中的相應表中。

NHibernate(版本2.0.1 GA)是如何完成的?

(PS:使用.NET 3.5 SP1,VS2008 SP1)

+0

是您的收藏有序?我的意思是:您是否期望在存儲數據庫並從數據庫中取回數據後,它們的順序相同? – 2009-05-05 13:36:42

+0

收藏必須以我向其添加項目的方式進行存儲。因此,添加orderA,orderB,orderC並再次讀取它,它必須按此順序保持orderA,orderB和orderC。 – 2009-05-05 14:00:23

回答

4

這是這樣完成的:

這樣創建類:

public class Customer : Contact 
{ 
    private ISet<Order> _orders = new HashedSet<Order>(); 

    public Collection<Order> Orders 
    { 
     return new List<Order>(_orders); 
    } 

    // NOrmally I would return a ReadOnlyCollection<T> instead of a Collection<T> 
    // since I want to avoid that users add Orders directly to the collection. 
    // If your relationship is bi-directional, then you have to set the other 
    // end of the association as well, in order to hide this for the programmer 
    // I always create add & remove methods (see below) 

    public void AddOrder(Order o) 
    { 
     if(o != null && _orders.Contains(o) == false) 
     { 
     o.Customer = this; 
     _orders.Add(o); 
     } 
    } 
} 
在映射

,你指定了這個:

<set name="Orders" table="OrdersTable" access="field.camelcase-underscore" inverse="true"> 
    <key column="..." /> 
    <one-to-many class="Order" .. /> 
</set> 

既然你使用繼承,你應該明確地看看不同的可能性關於繼承映射在NHibernate的,並選擇最適合自己情況的策略IES: inheritance mapping

關於設置&袋語義: - 當你映射一個集合爲一組,你可以確保所有映射集合中的實體是唯一的。也就是說,NHibernate將確保在重構​​實例的同時,集合不會包含重複項。 - 將集合映射爲包時,從數據庫加載對象時,您的集合可能會多次包含相同的實體。

  • 一個集合是一個整體被認爲是不同的對象的集合。 A 一組(字母) 的有效示例是:{a,b,c,d}。每個字母 只發生一次。
  • 一個袋子是一個集合的泛化。 A 包的成員可以有多個 一個成員資格,而 集的每個成員只有一個成員資格。一個有效的袋子例子是{a,a,a,b,c, c,d,...}。字母a和c 在包中出現多次。
+0

你的速度更快...繼承的描述,以及 - http://ayende.com/Blog/archive/2009/04/10/nhibernate-mapping-ndash-inheritance.aspx – Rashack 2009-05-05 12:18:13

1

,如果你不喜歡用一套從Iesi填入收藏

public class Customer : Contact 
{ 
    public ICollection<Order> Orders 
    { 
     get; private set; 

    } 
} 

和映射這樣的另一種解決方案:

<bag name="Orders" table="Customer_Orders" > 
    <key column="Customer_FK" /> 
    <composite-element> 
    <property name="OrderNumber" /> 
    <property name="OrderName" /> 
    <!-- ... --> 
    </composite-element> 
</set>