双向一对多实体关联

时间:2009-03-23 10:48:15

标签: nhibernate bidirectional

如果我有两个对象,比如ProductOrder和Product,我希望两者都能包含对另一个的多个引用,例如。

多个订单可以引用产品 ProductOrder可以包含多个产品。

我试图这样做......

  <set name="Products" inverse ="true" cascade="save-update">
      <key column="OrderID"/>
      <one-to-many class="Product"/>
  </set>

public class ProductOrder
{
    private ISet<Product> products = new HashedSet<Product>();

    public virtual int ID { get; set; }
    public virtual Customer Customer { get; set; }
    public virtual int NumberOfProducts { get; set; }
    public virtual decimal TotalCost { get; set; }
    public virtual void AddProduct (Product product)
    {
        products.Add(product);
    }
    public virtual ISet<Product> Products
    {
        get { return this.products; } 
        set { this.products = value; }
    }        
}


<set name="Orders" lazy="true" table="ProductOrders">
  <key column="ProductID"/>
  <one-to-many class="ProductOrder"/>
</set>


public class Product
{
    //public virtual Guid Id { get; set; }  //Could use Guid, though it's not really readable and harder to find reference in the DB

    private ISet<ProductOrder> orders = new HashedSet<ProductOrder>();

    public virtual int ID { get; set; }
    public virtual string Name { get; set; }
    public virtual string Category { get; set; }
    public virtual int Count { get; set; }
    public virtual bool Discontinued { get; set; }
    public virtual void AddOrder(ProductOrder order)
    {
        orders.Add(order);
    }
    public virtual ISet<ProductOrder> Orders
    {
        get { return this.orders; }
        set { this.orders = value; }
    }  
}

我无法设法让它按照我的预期运作。有什么建议吗?

2 个答案:

答案 0 :(得分:1)

从您的代码中,我认为这不是一对多,而是多对多的关系?看看http://nhibernate.info/doc/nh/en/index.html#collections-ofvalues

答案 1 :(得分:0)

恕我直言,你不应该映射Product.Orders关系。通常,您不希望在可能从数据库中提取大型集合的域对象上映射可能较大的集合。

如果您的订单开始变大,您将开始遇到性能问题。