Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Do a transactional batch of operations against the same partition key value in Azure Cosmos DB .NET SDK
using Microsoft.Azure.Cosmos;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
// Use the transactional batch capability in .NET SDK V3.4 or higher
namespace CosmosBatchSample
{
class Program
{
static async Task Main(string[] args)
{
string databaseId = "CosmosDatabase";
string containerId = "CosmosContainer";
using (var cosmosClient = new CosmosClient("endpoint", "key"))
{
// Get the container
var container = cosmosClient.GetDatabase(databaseId).GetContainer(containerId);
// We'll do a transactional batch across these items, which all share the partition key value for Username: "Alice"
var todoItem1 = new TodoItem()
{
id = Guid.NewGuid().ToString(),
Username = "alice",
Task = "Get started with Azure Cosmos DB!",
Status = "Done"
};
var todoItem2 = new TodoItem()
{
id = Guid.NewGuid().ToString(),
Username = "alice",
Task = "Import data into a container",
Status = "In-progress"
};
var todoItem3 = new TodoItem()
{
id = Guid.NewGuid().ToString(),
Username = "alice",
Task = "Run queries against the container ",
Status = "Planned"
};
// Create and execute the batch of operations
using (TransactionalBatchResponse batchResponse = await container.CreateTransactionalBatch(new PartitionKey("alice"))
.CreateItem<TodoItem>(item: todoItem1)
.ReplaceItem<TodoItem>(id: todoItem2.id, item: todoItem2)
.UpsertItem<TodoItem>(item: todoItem3)
.DeleteItem(id: todoItem2.id)
.ExecuteAsync())
{
if (!batchResponse.IsSuccessStatusCode)
{
// Handle and log exception
return;
}
// Look up interested results - eg. via typed access on operation results
TransactionalBatchOperationResult<TodoItem> replaceResult = batchResponse.GetOperationResultAtIndex<TodoItem>(1);
TodoItem todoItem2Resource = replaceResult.Resource;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment