我有一個Contact(基類),一個叫做Customer的類和一個叫做Supplier的類。客戶和供應商類別均來自Contact。如何在NHibernate中映射集合<T>?
客戶與訂單有0..n的關係。我想要在客戶端擁有一個Collection屬性,並將其映射到NHibernate中的相應表中。
NHibernate(版本2.0.1 GA)是如何完成的?
(PS:使用.NET 3.5 SP1,VS2008 SP1)
我有一個Contact(基類),一個叫做Customer的類和一個叫做Supplier的類。客戶和供應商類別均來自Contact。如何在NHibernate中映射集合<T>?
客戶與訂單有0..n的關係。我想要在客戶端擁有一個Collection屬性,並將其映射到NHibernate中的相應表中。
NHibernate(版本2.0.1 GA)是如何完成的?
(PS:使用.NET 3.5 SP1,VS2008 SP1)
這是這樣完成的:
這樣創建類:
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將確保在重構實例的同時,集合不會包含重複項。 - 將集合映射爲包時,從數據庫加載對象時,您的集合可能會多次包含相同的實體。
你的速度更快...繼承的描述,以及 - http://ayende.com/Blog/archive/2009/04/10/nhibernate-mapping-ndash-inheritance.aspx – Rashack 2009-05-05 12:18:13
,如果你不喜歡用一套從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>
是您的收藏有序?我的意思是:您是否期望在存儲數據庫並從數據庫中取回數據後,它們的順序相同? – 2009-05-05 13:36:42
收藏必須以我向其添加項目的方式進行存儲。因此,添加orderA,orderB,orderC並再次讀取它,它必須按此順序保持orderA,orderB和orderC。 – 2009-05-05 14:00:23