你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

Container.CreateTransactionalBatch(PartitionKey) 方法

定义

初始化 的新实例,该实例 TransactionalBatch 可用于以事务方式使用提供的分区键跨容器中的多个项执行操作。

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

参数

partitionKey
PartitionKey

批处理中所有项目的分区键。

返回

TransactionalBatch 的新实例。

示例

此示例以原子方式将一组文档修改为批处理。

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;
}

此示例以原子方式将一组文档作为批读取。

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());
        }
    }
}

注解

事务性Batch 请求的限制

适用于