You are developing a telemetry ingestion service that processes device events using the Azure Cosmos DB .NET SDK v3. The service uses a container configured with a partition key path of `/tenantId`.
You need to implement a helper method that performs two operations as a single transaction:
1. Create a new telemetry record of type `DeviceLog`.
2. Upsert a summary record of type `TenantSummary`.
Both records share the same `tenantId` value.
Which two of the following code segments should you use to complete the implementation?
- TransactionalBatch batch = container.CreateTransactionalBatch(new PartitionKey(tenantId))
.CreateItem<DeviceLog>(log)
.UpsertItem<TenantSummary>(summary);Answer - using (TransactionalBatchResponse response = await batch.ExecuteAsync())Answer
- CTransactionalBatch batch = container.CreateTransactionalBatch()
.CreateItem<DeviceLog>(log, new PartitionKey(tenantId))
.UpsertItem<TenantSummary>(summary, new PartitionKey(tenantId)); - Dusing (TransactionalBatchResponse response = await batch.ExecuteAsync(new ItemRequestOptions
{
SessionToken = "tenant-session-token"
}))
Answer
The correct segments are the one that initializes the transactional batch by passing the partition key to the CreateTransactionalBatch method and fluently chains CreateItem and UpsertItem, and the one that executes the batch using await batch.ExecuteAsync() within a using block.
The correct segments are the one that initializes the batch with a partition key and chains the operations, and the one that executes the batch asynchronously in a using block. In the .NET SDK v3, a transactional batch is created on a container by passing the PartitionKey to CreateTransactionalBatch. Operations are chained without specifying partition keys because the entire batch is restricted to the same partition. The execution of the batch is asynchronous and returning a response that should be disposed.
Step-by-Step Solution
Key Concept
Transactional batch execution in Azure Cosmos DB .NET SDK v3 requires declaring the partition key at the batch initialization level and executing the batch asynchronously using the correct request options.