-
Notifications
You must be signed in to change notification settings - Fork 24
Transactions
Transactions are supported within MicroLite using the syntax you will have seen in the examples in the Getting Started guide:
using (var transaction = session.BeginTransaction())
{
...
transaction.Commit();
}
You may wonder why the read queries are also performed in a transaction. The reason is that if you don't explicitly specify a transaction yourself, the database is going to implicitly create one itself. This adds overhead to the database and also means that if you have multiple reads which are not scoped inside the same transaction, you could get inconsistent results.
You may notice that in all of the examples, we haven't wrapped the call to .Commit()
in a try/catch
block with a transaction.Rollback();
in the catch
block. This is because MicroLite will automatically rollback the transaction when it is disposed if there is an exception when committing.
Do you need to manually call rollback? Maybe, if you have done some work in a transaction but decide whether to commit or rollback on another condition, you could write something like this:
using (var transaction = session.BeginTransaction())
{
...
if (some condition is still true)
{
transaction.Commit();
}
else
{
transaction.Rollback();
}
}