You are developing a .NET microservice that processes user orders in a multi-tenant SaaS application. Each tenant has their own partition in an Azure Cosmos DB SQL API container, and all operations within a single order lifecycle must be executed within a single transaction. You need to write C# code using the Azure Cosmos DB .NET SDK v3 to configure the client, access the container, and run a transactional batch of operations. In which sequence should you perform the steps to configure the client and execute the transactional batch?
- 1Instantiate the CosmosClient using a connection string and custom CosmosClientOptions to configure connection properties.
- 2Retrieve a Container reference by calling GetDatabase and then GetContainer from the CosmosClient instance.
- 3Create a PartitionKey object passing the value of the partition key for the specific tenant.
- 4Call CreateTransactionalBatch on the Container reference, passing the PartitionKey object.
- 5Chain operations like CreateItem or ReplaceItem to the TransactionalBatch instance, and then call ExecuteAsync to execute the transaction.
Answer
To perform a transactional batch operation in Azure Cosmos DB using the .NET SDK v3, you must first initialize a singleton CosmosClient with the required options. Next, obtain the Database and Container references. Since transactional batches operate on a single logical partition, you must define the PartitionKey. Then, initialize the TransactionalBatch using CreateTransactionalBatch on the container with the partition key. Finally, chain the operations onto the batch and call ExecuteAsync.
The correct sequence starts with client initialization (CosmosClient), followed by drilling down to the specific database and container references. Because transactional batching in Azure Cosmos DB requires operations to share the same partition key, the PartitionKey instance must be defined prior to calling CreateTransactionalBatch on the container. Finally, individual operations are chained to the batch, and ExecuteAsync is called to execute the entire transaction.
Step-by-Step Solution
Key Concept
Initiating CosmosClient, obtaining Container references, constructing a PartitionKey, and executing a TransactionalBatch with .NET SDK v3.