views:

13

answers:

0

We have Product, Category and ProductToCategory classes.

A product has many ProductToCategories, a category has many ProductToCategories.

Product includes this property

public virtual IList<ProductToCategory> Categories { get; set; }

ProductToCategory

public class ProductToCategory : Entity
{        
    public virtual Product Product { get; set; }        
    public virtual Category Category { get; set; }
    public virtual bool IsFeatured { get; set; }
}

Category includes these properties

    public virtual Category Parent { get; set; }
    public virtual IEnumerable<Category> Children { get; set; }
    public virtual IEnumerable<ProductToCategory> Products { get; set; }

We need an explicit ProductToCategory class because we need a boolean property on the relationship between products and categories to determine if this product should be featured on the home page for the category.

Mapping for all of this is using Fluent NHibernate AutoMapping with some overrides

Product Mapping Override

mapping.HasMany(x => x.Categories)
  .Cascade.AllDeleteOrphan()
  .Inverse();

Category Mapping Override

mapping.HasMany(x => x.Children)
  .Cascade.AllDeleteOrphan()
  .KeyColumn("ParentId");

mapping.References(x => x.Parent).Column("ParentId");

Product To Category Mapping Override

mapping.References(x => x.Category);

When I want save a product, I need NHibernate to remove any existing ProductToCategories linked to the product, and add in the ones which have been passed through from the UI whilst also updating the other product properties such as name, part number etc.

What would be the most concise way to ensure NHibernate saves the changes to the Product (including the linked ProductToCategories) when provided with an instance of my Product class.