Q84. How to insert multiple records in a transaction using TableBatchOperation?

As you know, Azure Table Storage supports entity batch transactions to manage multiple entities in a single transaction. Assume you’re trying to insert some entities in an Azure table using entity batch transaction. The following code example creates three entity objects and adds each to a TableBatchOperation using the Insert method. Then CloudTable.Execute is called to execute the operation.

CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

CloudTableClient cloudTableClient = storageAccount.CreateCloudTableClient();

var customer = new CustomerEntity()
{
    FirstName = "John",  LastName = "wayne"
};

CloudTable table = cloudTableClient.GetTableReference(tableName);

TableBatchOperation batchOperation = new TableBatchOperation();

batchOperation.Insert(customer);

customer = new CustomerEntity()
{
    FirstName = "Chris", LastName = "Gayle"
};

batchOperation.Insert(customer);

customer = new CustomerEntity()
{
    FirstName = "Marlon",   LastName = "Brando"
};

batchOperation.Insert(customer);
table.ExecuteBatch(batchOperation);