Is there a difference between Session.Save
and Transaction.Commit
?
When I should use which?
It seems that sometimes Session.Save
must use in conjunction with Transaction.Commit
, sometimes no. Can anyone tell why this is so?
They're differenrt-- Session.Save
saves an object and Transaction.Commit
commits a bunch of work (multiple Gets, Loads, Saves, Updates, etc).
You'll want to use both. Here's a quick explanation with a link for more reading. The NHibernate documentation says the following:
In an
ISession
, every database operation occurs inside a transaction that isolates the database operations (even read-only operations).
If you don't explicitly define your transaction, one will be created implicitly every time you read from or write to the database. Not very efficient. So even if you're just reading, you'll want to put everything inside a transaction and commit the transaction when you're done. Ayende Rahien explains further in this blog post.
When you look at some code samples out there, it may seem like people aren't using transactions but they may just be beginning/committing the transaction outside of the code you're looking at. In my ASP.Net MVC app, for example, I use an action filter (TransactionAttribute) to handle the transaction outside of my Controller Actions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With