Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nhibernate - item gets its ParentID updated to null instead of being deleted

The business logic inside a process is:

  • begin transaction
  • add an item to a collection
  • perform a find("somethingA")
  • delete that item depending on the previous step.
  • commit transaction

Im using cascade all-delete-orphans, and the inverse=true, both in my parent class. When removing the item from the collection, I set the .parentObj = null and remove the item from the collection.

When using TemplateFlushMode.Auto, I profiled the Database and the following is done:

  • INSERT item
  • SELECT related tosomethingA
  • UPDATE parentID (the FK to the parent) of the Item to NULL

(the insert item is done because a find() is done, to guarantee data consistency in the database). The the select is done, and then I would expect a DELETE to be performed... but an update to parentID = null is done.

When performing a Session.Flush() right before the Find(), the following happens:

  • INSERT item
  • SELECT related tosomethingA
  • DELETE Item

When using TemplateFlushMode.Commit, the changes are done at the end of the transaction and the item is never inserted:

  • SELECT related tosomethingA

The app I'm working with is using TemplateFlushMode.Auto, so I'm wondering, ,is there an explanation why the cascading is not working if a select is done in between one item is added and then removed in the same transaction?

I know the first answer that comes up is "don't add an item to a collection, if it will be removed afterwards". But I rather don't change the business logic.

Does anyone know why an update is being done instead of a delete when using AUTO? (when using Commit it does not insert the object)

like image 917
Adrián Poplavsky Avatar asked Dec 11 '11 02:12

Adrián Poplavsky


1 Answers

I guess you should use the cascade="delete" option in your mapping file in order to cascade on delete

like image 141
Helikaon Avatar answered Nov 08 '22 09:11

Helikaon