我有一个联系人类(基类)、一个名为“客户”的类和一个名为“供应商”的类。客户和供应商类都派生自联系人。
客户与订单有 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 中继承映射的不同可能性,并选择最适合您情况的策略:继承映射 http://www.nhforge.org/doc/nh/en/index.html#inheritance
关于 set 和 bag 语义:
- 当您将集合映射为集合时,您可以确保映射集合中的所有实体都是唯一的。也就是说,NHibernate 将确保在重建实例时,集合不会包含重复项。
- 当您将集合映射为包时,从数据库加载对象时,您的集合可能会多次包含相同的实体。
- Set 是不同的集合
对象被视为一个整体。 A
一组(字母)的有效示例
是:{a,b,c,d}。每个字母
恰好发生一次。
- Bag 是一个集合的概括。 A
一个包的成员可以拥有多于
一个会员资格,而每个会员
set 只有一个成员资格。一个有效的
袋子的例子是 { a, a, a, b, c,
光盘, ...}。字母a和c
多次出现在袋子中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)