ヘッダー
C# サンプル集
 

テーブルAPI ですべてのエンティティを取得する

2021/6/6

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

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

Azure Cosmos DB Table API の概要 | Microsoft Docs

 

 

テーブルにあるすべてのエンティティを取得する

前提

  • 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");

//▼実行
TableQuery query = new TableQuery();
//query = query.Take(5); // ←取得する最大件数を絞りたい場合

foreach (var entity in table.ExecuteQuery(query))
{
    System.Diagnostics.Debug.Write(entity.PartitionKey + "\t");
    System.Diagnostics.Debug.Write(entity.RowKey + "\t");
    //ここから下はエンティティに含まれるプロパティによって変更する必要があります。
    System.Diagnostics.Debug.Write(entity.Properties["birthDay"] + "\t");
    System.Diagnostics.Debug.Write(entity.Properties["note"]);
    System.Diagnostics.Debug.WriteLine("");
}

Debug.WriteLineが表示される場所

 

 

テーブルにあるすべてのエンティティを取得し、クラスにマッピングする

この例では、PartitionKey が "家康"、 RowKey が"徳川"であるエンティティを取得します。

前提

  • 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");

//▼実行
TableQuery<PersonEntity> query = new TableQuery<PersonEntity>();
//query = query.Take(5); // ←取得する最大件数を絞りたい場合

foreach (PersonEntity entity in table.ExecuteQuery(query))
{
    System.Diagnostics.Debug.Write(entity.PartitionKey + "\t");
    System.Diagnostics.Debug.Write(entity.RowKey + "\t");
    //ここから下はエンティティに含まれるプロパティによって変更する必要があります。
    System.Diagnostics.Debug.Write(entity.birthDay.ToString() + "\t");
    System.Diagnostics.Debug.Write(entity.note);
    System.Diagnostics.Debug.WriteLine("");
}

Debug.WriteLineが表示される場所

 

この例で使用している 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プロパティを直接使用する方法もあります。

 

 

テーブルにあるすべてのエンティティを取得し、JSONで表現する

前提

  • 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");

//▼実行
TableQuery<PersonEntity> query = new TableQuery<PersonEntity>();
//query = query.Take(5); // ←取得する最大件数を絞りたい場合

var entities = table.ExecuteQuery(query);

//結果をJSON化。
//日本語の文字列などはエンコードされて確認しにくいので、この例ではエンコードしないようにオプション設定します。
var option = new System.Text.Json.JsonSerializerOptions();
option.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
option.WriteIndented = true; //ついでに、改行とインデントで整形します。
string json = System.Text.Json.JsonSerializer.Serialize(entities, option);

//[別解]日本語の文字列などがエンコードされても良い場合は、次の1行だけでJSON化できます。
//string json = System.Text.Json.JsonSerializer.Serialize(entities);

//取得した全エンティティをJSONで出力します。
System.Diagnostics.Debug.WriteLine("取得したエンティティ: \n" + json);

Debug.WriteLineが表示される場所

メモ:この例で使用している PersonEntity は 上述の例 と同じです。

メモ:プロパティに System.Text.Json.Serialization.JsonIgnore 属性を付けると、そのプロパティはJSON化の対象外にできます。

 

参考

.NET Standard SDK を使用した Azure Cosmos DB Table API | Microsoft Docs

クイック スタート:.NET での Table API の使用 - Azure Cosmos DB | Microsoft Docs