Skip to content

Instantly share code, notes, and snippets.

@deborahc
Last active September 14, 2022 11:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save deborahc/6be9e6610a8621ab5e6079a2f2363309 to your computer and use it in GitHub Desktop.
Save deborahc/6be9e6610a8621ab5e6079a2f2363309 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: 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
BatchOperationResult<TodoItem> replaceResult = batchResponse.GetOperationResultAtIndex<TodoItem>(1);
TodoItem todoItem2Resource = replaceResult.Resource;
}
}
}
}
}
@sh1605
Copy link

sh1605 commented Jan 6, 2020

I believe line 50 should be
.ReplaceItem<TodoItem>(id: todoItem1.id, item: todoItem2)
Right?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment