Skip to content

Transactions

Stelio Kontos edited this page Sep 25, 2023 · 9 revisions

PetaPoco supports all forms of ADO.NET transactions and includes its own depth tracking (nesting) transaction support.

Isolation Levels

Fluent configuration

var db = config.Build()
         .UsingConnectionString("cs")
         .UsingProvider<SqlServerDatabaseProvider>()
         .UsingIsolationLevel(IsolationLevel.Chaos)
         .Create();

Constructor configuration

var db = new Database("MyConnectionStringName") { IsolationLevel = IsolationLevel.Chaos };

Transactions

PetaPoco depth tracking transactions

var db = new Database();

try
{
    db.BeginTransaction();

    // Some transactional DB work

    db.CompleteTransaction();
}
catch (Exception e)
{
    db.AbortTransaction();
}

PetaPoco depth tracking transactions with using syntax

var db = new Database();

using (var transaction = db.GetTransaction())
{
    // Some transactional DB work

    transaction.Complete();
}

Ambient transactions

var config = DatabaseConfiguration.Build()
               .UsingCommandTimeout(180);

using (TransactionScope scope = new TransactionScope())
{
    var db = config.Create();

    // Some transactional DB work

    scope.Complete();
}

What is depth tracking?

Some provider support multiple nested transaction, such SQL Server, but others do not. So that PetaPoco just works, out the box it has it's own depth tracking transaction. The code below illustrates how this works.

var db = new Database();

try
{
    db.BeginTransaction();

    // Some transactional DB work

    try
    {
        db.BeginTransaction();

        // Some transactional DB work

        try
        {
            db.BeginTransaction();

            // Some transactional DB work

            db.CompleteTransaction();
        }
        catch (Exception e)
        {
            db.AbortTransaction();
        }

        db.CompleteTransaction();
    }
    catch (Exception e)
    {
        db.AbortTransaction();
    }

    db.CompleteTransaction();
}
catch (Exception e)
{
    db.AbortTransaction();
}