Skip to content

Instantly share code, notes, and snippets.

@sh1605
Forked from deborahc/CosmosTransactionalBatch.cs
Last active January 6, 2020 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sh1605/f3575f89e6eb1c82f9ac495dd3ed905a to your computer and use it in GitHub Desktop.
Save sh1605/f3575f89e6eb1c82f9ac495dd3ed905a to your computer and use it in GitHub Desktop.
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 (BatchResponse batchResponse = await container.CreateBatch(new PartitionKey("alice"))
.CreateItem<TodoItem>(item: todoItem1)
.ReplaceItem<TodoItem>(id: todoItem1.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
BatchOperationResult<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