how to delete fk children in nhibernate
- by frosty
I would like to delete the ICollection PriceBreaks from Product.
I'm using the following method. However they dont seem to delete. What am i missing.
When i step thru. i notice that "product.PriceBreaks.Clear();" doesn't actually clear the items. Do i need to flush or something?
public void RemovePriceBreak(int productId)
{
using (ISession session = EStore.Domain.Helpers.NHibernateHelper.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
var product = session.Get<Product>(productId);
product.PriceBreaks.Clear();
session.SaveOrUpdate(product);
transaction.Commit();
}
}
Here are my hbm files
<class name="Product" table="Products">
<id name="Id" type="Int32" column="Id" unsaved-value="0">
<generator class="identity"/>
</id>
<property name="CompanyId" column="CompanyId" type="Int32" not-null="true" />
<property name="Name" column="Name"/>
<set name="PriceBreaks" table="PriceBreaks" generic="true" cascade="all-delete-orphan" inverse="true" >
<key column="ProductId" />
<one-to-many class="EStore.Domain.Model.PriceBreak, EStore.Domain" />
</set>
</class>
<class name="PriceBreak" table="PriceBreaks">
<id name="Id" type="Int32" column="Id" unsaved-value="0">
<generator class="identity"/>
</id>
<many-to-one name="Product" column="ProductId" not-null="true" cascade="all" class="EStore.Domain.Model.Product, EStore.Domain" />
</class>
My Entities
public class Product
{
public virtual int Id { get; set; }
public virtual ICollection<PriceBreak> PriceBreaks { get; set; }
public virtual void AddPriceBreak(PriceBreak priceBreak)
{
priceBreak.Product = this;
PriceBreaks.Add(priceBreak);
}
}
public class PriceBreak
{
public virtual int Id { get; set; }
public virtual Product Product { get; set; }
}