views:

207

answers:

2

If I have two objects, say ProductOrder and Product, I want both to be able to contain multiple references to the other, e.g.

A Product can be referenced by multiple Orders A ProductOrder can contain multiple Products.

I've attempted to do it as such...

  <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; }
    }  
}

I just can't manage to get it working as I'd expect it to. any suggestions?

A: 

IMHO, you shouldn't be mapping Product.Orders relationship. In general, you do not want to map potentially large collections on a domain object that could pull a large collection from the database.

If your orders start becoming large, you'll start running into performance problems.

Brian Chavez
+1  A: 

From your code, I think it's not an one-to-many but a many-to-many relationship ? Have a look to http://nhforge.org/doc/nh/en/index.html#collections-ofvalues

Matthieu