Transactions

Chris Skardon edited this page Feb 5, 2016 · 6 revisions

Released in version: 1.1.0.1

Important Note for Async Users

To use Transactions with async, you need to be compiling agains .NET 4.5.1 or higher, this is because the TransactionScope only started supporting async with 4.5.1

Basic Rules

Use Neo4jClient as you would normally, to execute in a transaction, wrap your calls in a TransactionScope

Committing a transaction

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

var txClient = (ITransactionalGraphClient) client;
using(var tx = txClient.BeginTransaction())
{
    client.Cypher.Create("(n:Tx {Value:'Test'})").ExecuteWithoutResults();
    client.Cypher.Create("(n:Tx {Value:'Test2'})").ExecuteWithoutResults();
    tx.Commit();
}

Rollback

Rollback is as simple as just not calling Complete(), the below code will not create anything in the database:

using(var scope = new TransactionScope())
{
    client.Cypher.Create("(n:Tx {Value:'Test'})").ExecuteWithoutResults();
    client.Cypher.Create("(n:Tx {Value:'Test2'})").ExecuteWithoutResults();
    //No Complete() call, so rolling back
}

Async

To use the TransactionScope with async, assuming you're compiling against .NET 4.5.1 or higher, you construct the TransactionScope using the TransactionScopeAsyncFlowOption parameter:

using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
    await client.Cypher.Create("(n:Tx {Name:'Test'})").ExecuteWithoutResultsAsync();
    scope.Complete();
}
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.