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

2

8

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)

Offer answered 11/12, 2011 at 2:12 Comment(3)
Hey Adrián, good question, I have the same question as you actually.Febrifacient
Can I ask what are you trying to accomplish with this? it may be a different solution.Acetify
This is a common ORM issue, and NH handles it via a combination of relational, cascade and null directives. As @giammin says, it would best if you posted your mappings.Thierry
W
1

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

Wiggins answered 2/2, 2012 at 10:7 Comment(0)
E
0

Are you using a two way one to many binding ? Have you marked not-null="true" on the foreign key in the details table ? Can you please post your mappings XML file for better understanding ?

I know that i haven't answered your question, but I do not have enough reputation to post a comment instead.

Exterior answered 26/12, 2011 at 9:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.