NHibernate saving "middle man" with has many association
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 th开发者_如何学Cis 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.
If the product instance coming from the UI is not associated with the nhibernate session but is a persistent entity (has valid identity) then session.Merge(instance)
or session.SaveOrUpdateCopy(instance)
should do the trick. They will get the copy of this entity from the DB and save the changes between your instance and the DB-instance.
精彩评论