Container.CreateTransactionalBatch(PartitionKey) Method

Definition

Initializes a new instance of TransactionalBatch that can be used to perform operations across multiple items in the container with the provided partition key in a transactional manner.

public abstract Microsoft.Azure.Cosmos.TransactionalBatch CreateTransactionalBatch (Microsoft.Azure.Cosmos.PartitionKey partitionKey);
abstract member CreateTransactionalBatch : Microsoft.Azure.Cosmos.PartitionKey -> Microsoft.Azure.Cosmos.TransactionalBatch
Public MustOverride Function CreateTransactionalBatch (partitionKey As PartitionKey) As TransactionalBatch

Parameters

partitionKey
PartitionKey

The partition key for all items in the batch.

Returns

TransactionalBatch

A new instance of TransactionalBatch.

Examples

This example atomically modifies a set of documents as a batch.

public class ToDoActivity
{
    public string type { get; set; }
    public string id { get; set; }
    public string status { get; set; }
}

string activityType = "personal";
ToDoActivity test1 = new ToDoActivity()
{
    type = activityType,
    id = "learning",
    status = "ToBeDone"
};

ToDoActivity test2 = new ToDoActivity()
{
    type = activityType,
    id = "shopping",
    status = "Done"
};

ToDoActivity test3 = new ToDoActivity()
{
    type = activityType,
    id = "swimming",
    status = "ToBeDone"
};

using (TransactionalBatchResponse batchResponse = await container.CreateTransactionalBatch(new Cosmos.PartitionKey(activityType))
    .CreateItem<ToDoActivity>(test1)
    .ReplaceItem<ToDoActivity>(test2.id, test2)
    .UpsertItem<ToDoActivity>(test3)
    .DeleteItem("reading")
    .CreateItemStream(streamPayload1)
    .ReplaceItemStream("eating", streamPayload2)
    .UpsertItemStream(streamPayload3)
    .ExecuteAsync())
{
   if (!batchResponse.IsSuccessStatusCode)
   {
       // Handle and log exception
       return;
   }

   // Look up interested results - eg. via typed access on operation results
   TransactionalBatchOperationResult<ToDoActivity> replaceResult = batchResponse.GetOperationResultAtIndex<ToDoActivity>(0);
   ToDoActivity readActivity = replaceResult.Resource;
}

This example atomically reads a set of documents as a batch.

string activityType = "personal";
using (TransactionalBatchResponse batchResponse = await container.CreateTransactionalBatch(new Cosmos.PartitionKey(activityType))
   .ReadItem("playing")
   .ReadItem("walking")
   .ReadItem("jogging")
   .ReadItem("running")
   .ExecuteAsync())
{
    // Look up interested results - eg. via direct access to operation result stream
    List<string> resultItems = new List<string>();
    foreach (TransactionalBatchOperationResult operationResult in batchResponse)
    {
        using (StreamReader streamReader = new StreamReader(operationResult.ResourceStream))
        {
            resultItems.Add(await streamReader.ReadToEndAsync());
        }
    }
}

Applies to