One of the things that get me thoroughly confused is the use of session.Flush
,in conjunction with session.Commit
, and session.Close
.
Sometimes session.Close
works, e.g., it commits all the changes that I need. I know I need to use commit when I have a transaction, or a unit of work with several creates/updates/deletes, so that I can choose to rollback if an error occurs.
But sometimes I really get stymied by the logic behind session.Flush
. I have seen examples where you have a session.SaveOrUpdate()
followed by a flush, but when I remove Flush it works fine anyway. Sometimes I run into errors on the Flush statement saying that the session timed out, and removing it made sure that I didn't run into that error.
Does anyone have a good guideline as to where or when to use a Flush? I've checked out the NHibernate documentation for this, but I still can't find a straightforward answer.
From time to time the ISession will execute the SQL statements needed to synchronize the ADO.NET connection's state with the state of objects held in memory.
And always use
after the changes are committed than this changes to save into database we use transaction.Commit();
Here are two examples of my code where it would fail without session.Flush():
http://www.lucidcoding.blogspot.co.uk/2012/05/changing-type-of-entity-persistence.html
at the end of this, you can see a section of code where I set identity insert on, save the entity then flush, then set identity insert off. Without this flush it seemed to be setting identity insert on and off then saving the entity.
The use of Flush() gave me more control over what was going on.
Here is another example:
Sending NServiceBus message inside TransactionScope
I don't fully understand why on this one, but Flush() prevented my error from happening.
Starting in NHibernate 2.0, transactions are required for DB operations. Therefore, the
ITransaction.Commit()
call will handle any necessary flushing. If for some reason you aren't using NHibernate transactions, then there will be no auto-flushing of the session.Briefly:
Close()
, instead wrap your calls on anISession
inside ausing
statement or manage the lifecycle of your ISession somewhere else.From the documentation:
...
Also refer to this section: