title: NHibernate: is it valid to call Session.Flush() before committing a transaction?
body: <p>I need to execute two operations inside a NHibernate's unit of work: a transactional one (an entity saving) and a not-transactional one.</p>
  
  <p>Since the not-transactional operation cannot be rollbacked, if I save the entity <strong>before</strong> executing the not-transactional operation (and finally committing the transaction) I still get a transactional behaviour:</p>
  
  <ul>
  <li>The operations will be committed only if the two sub-operations execute successfully;</li>
  <li>If the entity save fails, the not-transactional operation won't be executed;</li>
  <li>If the not-transactional fails, the entity save will be rollbacked.</li>
  </ul>
  
  <p>The problem: with a code like the following, NHibernate won't execute the actual sql insert until the call to transaction.Commit() (which calls session.Flush() internally):</p>
  
  <pre><code>        using (var transaction = session.BeginTransaction())
          {
              session.Save(entity);
              NotTransactionalOperationBasedOn(entity);
  
              transaction.Commit(); // the actual sql insert will be executed here
          }
  </code></pre>
  
  <p>With a code like this, if the Sql Insert fails it's too late: NotTransactionalOperation has been executed. To execute the actual SQL insert before executing NotTransactionalOperation I have to explicity call session.Flush() right before the session.Save():</p>
  
  <pre><code>        using (var transaction = session.BeginTransaction())
          {
              session.Save(entity);
              session.Flush(); // the actual sql insert will be executed here
  
              NotTransactionalOperationBasedOn(entity);
  
              transaction.Commit(); 
          }
  </code></pre>
  
  <p>The code works, but... is it considered a best practice to call session.Flush() before committing the transaction? If not, are there better ways to achieve the same result?</p>