c# - 如何在 NHibernate 中映射 Collection<T>?

标签 c# visual-studio-2008 nhibernate

我有一个联系人类(基类)、一个名为客户的类和一个名为供应商的类。 Customer 和 supplier 类都派生自 Contact。

Customer 与 Order 有 0..n 关系。我想在 customer 上有一个 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 中有关继承映射的不同可能性,然后选择最适合您情况的策略: inheritance mapping

关于集合和包的语义: - 当您将一个集合映射为一个集合时,您可以确保映射集合中的所有实体都是唯一的。也就是说,NHibernate 将确保在重构​​实例时集合不会包含重复项。 - 当您将集合映射为包时,从数据库加载对象时,您的集合可能会多次包含同一实体。

  • 集合是不同的集合 作为一个整体考虑的对象。一种 一组(字母)的有效示例 是:{a, b, c, d}。每个字母 恰好出现一次。
  • 包是集合的概括。一种 一个袋子的成员可以有超过 一个成员,而每个成员 set 只有一个成员。一个有效的 包的例子是 { a, a, a, b, c, c, d, ...}。字母a和c 在 Bag 中出现不止一次。

关于c# - 如何在 NHibernate 中映射 Collection<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/824587/

相关文章:

visual-studio - app.config中的用户范围与应用程序范围

c# - nHibernate 在多个线程上枚举相同的集合

c# - 删除抛出 "deleted object would be re-saved by cascade"

c# - 上午/下午到时间跨度

C# 在项目之间共享对象

c# - 创建证书时未处理的加密异常

c# - 为什么它一直在说 "cannot find table 0"?

oracle - VS2008 SSRS 用于查询 Oracle : How do I stop {oj} for outer Joins?

c# - 有条件地获取关联实体避免 SELECT N+1 问题

c# - 如何连接到 MySQL 数据库?