﻿# Transactional Session with Azure Table Persistence


In order to use the [transactional session feature](/nservicebus/transactional-session/index.md) with Azure Table Persistence, add a reference to the `NServiceBus.Persistence.AzureTable.TransactionalSession` NuGet package.

## Configuration

To enable the transactional session feature:

<!-- snippet: enabling-transactional-session-azurestorage -->

```cs
var persistence = config.UsePersistence<AzureTablePersistence>();
persistence.EnableTransactionalSession();
```

<!-- endsnippet -->

## Opening a session

To open an Azure Storage Persistence transactional session:

<!-- snippet: open-transactional-session-azurestorage -->

```cs
using var childScope = serviceProvider.CreateScope();
var session = childScope.ServiceProvider.GetService<ITransactionalSession>();
await session.Open(
        new AzureTableOpenSessionOptions(
            new TableEntityPartitionKey("MyPartitionKey")));

// use the session

await session.Commit();
```

<!-- endsnippet -->

### Configuring the table

The name of the destination table can be specified when opening the session:

<!-- snippet: open-transactional-session-azurestorage-table -->

```cs
using var childScope = serviceProvider.CreateScope();
var session = childScope.ServiceProvider.GetService<ITransactionalSession>();
await session.Open(
        new AzureTableOpenSessionOptions(
            new TableEntityPartitionKey("MyPartitionKey"),
            new TableInformation("MyTable")));

// use the session

await session.Commit();
```

<!-- endsnippet -->

## Transaction usage

Message and database operations made via the transactional session are committed together once the session is committed:

<!-- snippet: use-transactional-session-azurestorage -->

```cs
await session.Open(
        new AzureTableOpenSessionOptions(
            new TableEntityPartitionKey("MyPartitionKey")));

// add messages to the transaction:
await session.Send(new MyMessage());

// access the database:
var azureTableSession = session.SynchronizedStorageSession.AzureTablePersistenceSession();

await session.Commit();
```

<!-- endsnippet -->

See the [Azure table persistence transactions documentation](/persistence/azure-table/transactions.md#sharing-the-transaction) for further details about using the transaction.

> [!WARNING]
> In order to guarantee atomic consistency across message and database operations, the [outbox](/nservicebus/outbox/index.md) must be enabled. Otherwise `Commit` executes database modifications first and then messages are dispatched with best-effort.
