[英]How to map a Collection<T> in NHibernate?
I have a class Contact (base class),a class called Customer and a class called Supplier. 我有一个类Contact(基类),一个名为Customer的类和一个名为Supplier的类。 Customer and supplier class both derive from Contact.
客户和供应商类均来自Contact。
Customer has a 0..n relation with Order. 客户与订单的关系为0..n。 I want to have a Collection property on customer and have it mapped in NHibernate to its corresponding table.
我希望在客户上有一个Collection属性,并将它在NHibernate中映射到相应的表。
How is this done in NHibernate (version 2.0.1 GA) ? 这是如何在NHibernate(版本2.0.1 GA)中完成的?
(ps: using .NET 3.5 SP1, VS2008 SP1) (ps:使用.NET 3.5 SP1,VS2008 SP1)
This is done like this: 这样做是这样的:
Create your class like this: 像这样创建你的类:
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);
}
}
}
in your mapping, you specify this: 在您的映射中,您指定:
<set name="Orders" table="OrdersTable" access="field.camelcase-underscore" inverse="true">
<key column="..." />
<one-to-many class="Order" .. />
</set>
Since you use inheritance, you should definitly have a look at the different posibilities regarding inheritance-mapping in NHibernate, and choose the strategy that is best suited for your situation: inheritance mapping 既然你使用了继承,你应该明确地看看NHibernate中有关继承映射的不同可能性,并选择最适合你情况的策略: 继承映射
Regarding set & bag semantics: - when you map a collection as a set, you can be sure that all the entities in the mapped collection, are unique. 关于set&bag语义: - 当您将集合映射为集合时,可以确保映射集合中的所有实体都是唯一的。 That is, NHibernate will make sure that, while reconstituting an instance, the collection will not contain duplicates.
也就是说,NHibernate将确保在重构实例时,该集合不会包含重复项。 - when you map the collection as a bag, it is possible that your collection will contain the same entity more then once when loading the object from the DB.
- 当您将集合映射为包时,从数据库加载对象时,您的集合可能会包含多个相同的实体。
Another solution if you don't like to use the set from Iesi collections 另一种解决方案,如果您不喜欢使用Iesi集合中的集合
public class Customer : Contact
{
public ICollection<Order> Orders
{
get; private set;
}
}
And the mapping like this: 和这样的映射:
<bag name="Orders" table="Customer_Orders" >
<key column="Customer_FK" />
<composite-element>
<property name="OrderNumber" />
<property name="OrderName" />
<!-- ... -->
</composite-element>
</set>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.