ヘッダー
C# サンプル集
 

テーブルAPI でエンティティを複数挿入する

2021/6/6

→ Visual Basic のサンプルに切り替える

この記事は Azure Cosmos DB テーブル API を対象にしています。

Azure Cosmos DB Table API の概要 | Microsoft Docs

 

 

15個のエンティティを一度に挿入する

同じキーのエンティティが既に存在する場合例外が発生します。例外が発生した場合、すべての挿入が失敗します。

前提

  • Azure Cosmos DB のアカウントがあり、テーブルAPIのデータベース上に TestTable というテーブルが存在する。
  • NuGet で Microsoft.Azure.Cosmos.Table パッケージをインストールしている。 → NuGetの使用方法
  • using Microsoft.Azure.Cosmos.Table; がソースコードの冒頭付近に記載されている。

メモ:接続文字列の確認方法

//▼Cosmos DBに接続
//接続文字列は環境に応じて指定してください。
string connectionString = "DefaultEndpointsProtocol=https;AccountName=xxxxxx;AccountKey=U2V0IHlvdXIgYWNjb3VudCBrZXkgZnJvbSBhenVyZSBwb3J0YWw=;TableEndpoint=https://xxxxxx.table.cosmos.azure.com:443/;";
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

//▼テーブルへの参照を取得
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference("TestTable");

//▼追加操作を実行
//この例ではエンティティは PersonEntity クラスとしてあらかじめ定義されています。
var batch = new TableBatchOperation();
batch.Insert(new PersonEntity { firstName = "家康", lastName = "徳川", note = "江戸幕府初代将軍" });
batch.Insert(new PersonEntity { firstName = "秀忠", lastName = "徳川", note = "江戸幕府2代目将軍" });
batch.Insert(new PersonEntity { firstName = "家光", lastName = "徳川", note = "江戸幕府3代目将軍" });
batch.Insert(new PersonEntity { firstName = "家綱", lastName = "徳川", note = "江戸幕府4代目将軍" });
batch.Insert(new PersonEntity { firstName = "綱吉", lastName = "徳川", note = "江戸幕府5代目将軍" });
batch.Insert(new PersonEntity { firstName = "家宣", lastName = "徳川", note = "江戸幕府6代目将軍" });
batch.Insert(new PersonEntity { firstName = "家継", lastName = "徳川", note = "江戸幕府7代目将軍" });
batch.Insert(new PersonEntity { firstName = "吉宗", lastName = "徳川", note = "江戸幕府8代目将軍" });
batch.Insert(new PersonEntity { firstName = "家重", lastName = "徳川", note = "江戸幕府9代目将軍" });
batch.Insert(new PersonEntity { firstName = "家治", lastName = "徳川", note = "江戸幕府10代目将軍" });
batch.Insert(new PersonEntity { firstName = "家斉", lastName = "徳川", note = "江戸幕府11代目将軍" });
batch.Insert(new PersonEntity { firstName = "家慶", lastName = "徳川", note = "江戸幕府12代目将軍" });
batch.Insert(new PersonEntity { firstName = "家定", lastName = "徳川", note = "江戸幕府13代目将軍" });
batch.Insert(new PersonEntity { firstName = "家茂", lastName = "徳川", note = "江戸幕府14代目将軍" });
batch.Insert(new PersonEntity { firstName = "慶喜", lastName = "徳川", note = "江戸幕府15代目将軍" });

TableBatchResult result = table.ExecuteBatch(batch);
//非同期版もあります。
//TableBatchResult result = await table.ExecuteBatchAsync(batch);

//▼結果
//この操作で消費された要求ユニット(RU)の使用量を出力します。
if (result.RequestCharge.HasValue)
{
    System.Diagnostics.Debug.WriteLine("要求ユニット使用量: " + result.RequestCharge);
}

Debug.WriteLineが表示される場所

メモ:Insert の代わりに InsertOrMerge, InsertOrReplace, Marge なども使用できます。

メモ:対象のエンティティはすべて同じパーティションキーである必要があります。この例では lastName です。

メモ:最大で100個のエンティティを一度に挿入できます。通信量(ペイロード)は4MiBに制限されます。

 

この例で使用している PersonEntity は次の通りです。

PersonEntity クラス

public class PersonEntity : TableEntity
{
    [Microsoft.Azure.Cosmos.Table.IgnoreProperty]
    public string lastName { get => PartitionKey; set => PartitionKey = value; }
    [Microsoft.Azure.Cosmos.Table.IgnoreProperty]
    public string firstName { get => RowKey; set => RowKey = value; }
    public DateTime? birthDay { get; set; }
    public string note { get; set; }
}

メモ:エンティティは TableEntity を継承するのが楽です。この例ではキー項目にIgnoreProperty属性をつけて PartitionKey と RowKey にそれぞれマッピングしています。その代わりにPartitionKeyプロパティ、RowKeyプロパティを直接使用する方法もあります。

メモ:nullがあり得る構造体の型には ? を付けておきます。

 

 

エンティティ用のクラスを定義せずに、15個のエンティティを一度に挿入する

同じキーのエンティティが既に存在する場合例外が発生します。例外が発生した場合、すべての挿入が失敗します。

前述の例と異なり、エンティティを表すクラスを別途定義する必要はありません。

前提

  • Azure Cosmos DB のアカウントがあり、テーブルAPIのデータベース上に TestTable というテーブルが存在する。
  • NuGet で Microsoft.Azure.Cosmos.Table パッケージをインストールしている。 → NuGetの使用方法
  • using Microsoft.Azure.Cosmos.Table; がソースコードの冒頭付近に記載されている。

メモ:接続文字列の確認方法

//▼Cosmos DBに接続
//接続文字列は環境に応じて指定してください。
string connectionString = "DefaultEndpointsProtocol=https;AccountName=xxxxxx;AccountKey=U2V0IHlvdXIgYWNjb3VudCBrZXkgZnJvbSBhenVyZSBwb3J0YWw=;TableEndpoint=https://xxxxxx.table.cosmos.azure.com:443/;";
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

//▼テーブルへの参照を取得
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference("TestTable");

//▼追加操作を実行
var batch = new TableBatchOperation();

Func<string, string, string, DynamicTableEntity> entityOf =
    (string rowKey, string partitionKey, string note) =>
    {
        DynamicTableEntity entity = new DynamicTableEntity(partitionKey, rowKey);
        entity.Properties.Add("note", EntityProperty.GeneratePropertyForString(note));
        return entity;
    };

batch.Insert(entityOf("家康", "徳川", "江戸幕府初代将軍"));
batch.Insert(entityOf("秀忠", "徳川", "江戸幕府2代目将軍"));
batch.Insert(entityOf("家光", "徳川", "江戸幕府3代目将軍"));
batch.Insert(entityOf("家綱", "徳川", "江戸幕府4代目将軍"));
batch.Insert(entityOf("綱吉", "徳川", "江戸幕府5代目将軍"));
batch.Insert(entityOf("家宣", "徳川", "江戸幕府6代目将軍"));
batch.Insert(entityOf("家継", "徳川", "江戸幕府7代目将軍"));
batch.Insert(entityOf("吉宗", "徳川", "江戸幕府8代目将軍"));
batch.Insert(entityOf("家重", "徳川", "江戸幕府9代目将軍"));
batch.Insert(entityOf("家治", "徳川", "江戸幕府10代目将軍"));
batch.Insert(entityOf("家斉", "徳川", "江戸幕府11代目将軍"));
batch.Insert(entityOf("家慶", "徳川", "江戸幕府12代目将軍"));
batch.Insert(entityOf("家定", "徳川", "江戸幕府13代目将軍"));
batch.Insert(entityOf("家茂", "徳川", "江戸幕府14代目将軍"));
batch.Insert(entityOf("慶喜", "徳川", "江戸幕府15代目将軍"));

TableBatchResult result = table.ExecuteBatch(batch);
//非同期版もあります。
//TableBatchResult result = await table.ExecuteBatchAsync(batch);

//▼結果
//この操作で消費された要求ユニット(RU)の使用量を出力します。
if (result.RequestCharge.HasValue)
{
    System.Diagnostics.Debug.WriteLine("要求ユニット使用量: " + result.RequestCharge); // 108.87
}

Debug.WriteLineが表示される場所

メモ:Insert の代わりに InsertOrMerge, InsertOrReplace, Marge なども使用できます。

メモ:対象のエンティティはすべて同じパーティションキーである必要があります。

メモ:最大で100個のエンティティを一度に挿入できます。通信量(ペイロード)は4MiBに制限されます。

 

 

参考

エンティティグループトランザクションの実行 (REST API)-Azure Storage | Microsoft Docs