Forked from deborahc/CosmosTransactionalBatch.cs
Last active
November 5, 2019 22:52
-
-
Save andrewdmoreno/e93552ee0894dcbc1b403fe0b544c4bf 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 (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