Skip to content
Charlotte Skardon edited this page Feb 7, 2023 · 7 revisions

Every operation against the database is performed in a transaction. If it's a simple one off 'update' it is run in a self contained transaction and you don't need to worry about it.

This page concerns manually executing multiple queries in one transaction.

Start a transaction

var transaction = client.BeginTransaction();

You can (and best practice is to) use in a using statement:

using(ITransaction tx = client.BeginTransaction())
{
    /* CODE */
}

Rollback a transaction

There are two ways to rollback a transaction, implictly by disposing of an ITransaction instance, or calling RollbackAsync()

//Implicit
using(ITransaction tx = client.BeginTransaction())
{
} //Automatically rolled back

//Explicit
using(ITransaction tx = client.BeginTransaction())
{
    await tx.RollbackAsync();
}

Committing a transaction

Use the CommitAsync() method on the ITransaction to commit the transaction. The below code will create two nodes in the database.

using(ITransaction tx = txClient.BeginTransaction())
{
    await client.Cypher.Create("(n:Tx {Value:'Test'})").ExecuteWithoutResultsAsync();
    await client.Cypher.Create("(n:Tx {Value:'Test2'})").ExecuteWithoutResultsAsync();
    await tx.CommitAsync();
}