Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate updates row before deleting it?

I'm having a strange behavior with nhibernate. The problem is that nhibernate performs an update before it deletes an entity. I have a Category class and a Product class. Category has a bag of products. When I remove a product from Category, nhibernate does the following:

  • It updates the product entity which I removed from collection
  • It deletes the product entity from database.

Here's mapping

  <class name="Category"> 
    <id name="Id"> 
      <generator class="hilo" /> 
    </id> 
    <property name="Name" lazy="false" length="20" /> 

    <bag name="Products" cascade="all-delete-orphan" lazy="false" 
inverse="false"> 
      <key column="CategoryId" /> 
      <one-to-many class="Product" /> 
    </bag> 
  </class> 

  <class name="Product"> 
    <id name="Id"> 
      <generator class="hilo" /> 
    </id> 
    <property name="Name" lazy="false" /> 
    <property name="Discontinued" lazy="false" /> 
    <property name="Price" lazy="false" /> 
    <many-to-one name="Category" 
             class="Category" 
             column="CategoryId" 
             cascade="none" /> 
  </class>

Here's the code

    using (var session = NHibernateHelper.OpenSession()) 
    using (var transaction = session.BeginTransaction()) 
    { 
        var c1 = session.Load<Category>(32768); 
        c1.Ps.RemoveAt(0); 

        session.SaveOrUpdate(c1); 
        transaction.Commit(); 
    }

and here's the result:

exec sp_executesql N'UPDATE Product SET CategoryId = null WHERE 
CategoryId = @p0 AND Id = @p1',N'@p0 int,@p1 int',@p0=32768,@p1=65537 
go 

exec sp_executesql N'DELETE FROM Product WHERE Id = @p0',N'@p0 
int',@p0=65537 
go

Anyone can explain this strange behavior?

Thanks.

like image 586
Davita Avatar asked Jan 21 '11 21:01

Davita


1 Answers

Change inverse to true on your definition for your Products bag on Category. Setting inverse to false tells NHibernate that the Category objects is the owner of the key on the relationship.

With inverse set to false on the Products collection, NHibernate sees the Category as an owner of the relationship. So when the Products collection changes it issues the update statement to remove the Product from the Category. Then the delete occurs because the Product was deleted.

like image 159
shf301 Avatar answered Nov 10 '22 05:11

shf301