Last active
September 14, 2022 11:35
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I believe line 50 should be
.ReplaceItem<TodoItem>(id: todoItem1.id, item: todoItem2)
Right?