Skip to content
This repository has been archived by the owner on Dec 29, 2020. It is now read-only.

Transactions

Trevor Pilley edited this page May 15, 2014 · 1 revision

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.

Rollback

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();
    }
}
Clone this wiki locally