Nhibernate order of SQL statements when cleaning session

According to NHibernate documentation, SQL statements are issued in the following order when a session is cleared:

  • all object inserts, in the same order, the corresponding objects were saved using ISession.Save ()
  • all entity updates
  • delete all collections
  • delete, update, and insert collection items
  • all collection inserts
  • all entity deletions, in the same order corresponding objects were deleted using ISession.Delete ()

Why is this mandatory in this order and is there a way to change it so that the instructions are executed in the same order that I give them?

+7
source share
2 answers

In that order, because it is the safest.

And no, you cannot change the order. But also you never gave NHibernate any order: you simply mark entities for perseverance; NHibernate determines what to do automatically.

If you think you need more control over individual SQL operations, you can use IStatelessSession instead of a regular ISession . You lose everything that NH does automatically (lazy loading, caching, dirty tracking), but you can (should) explicitly indicate when an Insert , Delete or Update record is.

+3
source

You cannot change the order in which NHibernate generates SQL as described above, but you can break down the units of work.

eg:

 using(var transaction = Session.BeginTransaction()) { var company = Session.QueryOver<Company>().First(); var employee = new Employee{ ID = Guid.NewID() }; company.Employees.Add(employee); Session.Flush(); var carSpace = new CarParkingSpace { EmployeeID = employee.ID }; Session.Save(carSpace); transaction.Commit(); } 

Adding Session.Flush () - everything to this point will be transferred to the transaction. Without this, NHibernate will attempt to create a parking space allocated to a non-existing employee.

0
source

All Articles