C# サンプル集 |
Visual Basic 中学校 > C# サンプル集 > C# サンプル集目次 > Azure > Cosmos DB >
テーブルAPI でエンティティを1つ取得する
2021/5/23
この記事は Azure Cosmos DB テーブル API を対象にしています。
キーを指定してエンティティを取得する
この例では、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");
//▼取得操作を実行
TableOperation retreiveOperation = TableOperation.Retrieve("徳川","家康");
TableResult result = table.Execute(retreiveOperation);
//非同期版もあります。
//TableResult result = await table.ExecuteAsync(retreiveOperation);
//▼結果
//この操作で消費された要求ユニット(RU)の使用量を出力します。
if (result.RequestCharge.HasValue)
{
System.Diagnostics.Debug.WriteLine("要求ユニット使用量: " + result.RequestCharge);
}
//取得したエンティティ
if (result.Result != null)
{
dynamic entity = result.Result; //DynamicTableEntity
System.Diagnostics.Debug.WriteLine($"PartitionKey = {entity.PartitionKey}");
System.Diagnostics.Debug.WriteLine($"RowKey = {entity.RowKey}");
//ここから下はエンティティに含まれるプロパティによって変更する必要があります。
System.Diagnostics.Debug.WriteLine($"birthDay = {entity.Properties["birthDay"]}");
System.Diagnostics.Debug.WriteLine($"note = {entity.Properties["note"]}");
}
結果の出力例
要求ユニット使用量: 2
PartitionKey = 徳川
RowKey = 家康
birthDay = 1843-01-31T00:00:00.0000000Z
note = 幼名は竹千代
キーを指定してエンティティを取得し、クラスにマッピングする
この例では、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");
//▼取得操作を実行
TableOperation retreiveOperation = TableOperation.Retrieve<PersonEntity>("徳川","家康");
TableResult result = table.Execute(retreiveOperation);
//非同期版もあります。
//TableResult result = await table.ExecuteAsync(retreiveOperation);
//▼結果
//この操作で消費された要求ユニット(RU)の使用量を出力します。
if (result.RequestCharge.HasValue)
{
System.Diagnostics.Debug.WriteLine("要求ユニット使用量: " + result.RequestCharge);
}
//取得したエンティティ
if (result.Result != null)
{
PersonEntity entity = result.Result as PersonEntity;
System.Diagnostics.Debug.WriteLine($"PartitionKey = {entity.PartitionKey}");
System.Diagnostics.Debug.WriteLine($"RowKey = {entity.RowKey}");
//ここから下はエンティティに含まれるプロパティによって変更する必要があります。
System.Diagnostics.Debug.WriteLine($"birthDay = {entity.birthDay}");
System.Diagnostics.Debug.WriteLine($"note = {entity.note}");
}
結果の出力例
要求ユニット使用量: 2
PartitionKey = 徳川
RowKey = 家康
birthDay = 1843/01/31 0:00:00
note = 幼名は竹千代
この例で使用している 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として取得する
この例では、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");
//▼取得操作を実行
TableOperation retreiveOperation = TableOperation.Retrieve<PersonEntity>("徳川","家康");
TableResult result = table.Execute(retreiveOperation);
//非同期版もあります。
//TableResult result = await table.ExecuteAsync(retreiveOperation);
//▼結果
//この操作で消費された要求ユニット(RU)の使用量を出力します。
if (result.RequestCharge.HasValue)
{
System.Diagnostics.Debug.WriteLine("要求ユニット使用量: " + result.RequestCharge);
}
//取得したエンティティ
PersonEntity entity = result.Result as PersonEntity;
if (entity != null)
{
//結果を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(entity,option);
//[別解]日本語の文字列などがエンコードされても良い場合は、次の1行だけでJSON化できます。
//string json = System.Text.Json.JsonSerializer.Serialize(entity);
//取得したエンティティを出力します。
System.Diagnostics.Debug.WriteLine("取得したエンティティ: \n" + json);
}
メモ:この例で使用している PersonEntity は 上述の例 と同じです。
結果の出力例
要求ユニット使用量: 2
取得したエンティティ:
{
"lastName": "徳川",
"firstName": "家康",
"birthDay": "1843-01-31T00:00:00Z",
"note": "幼名は竹千代",
"PartitionKey": "家康",
"RowKey": "徳川",
"Timestamp": "2021-05-03T04:16:14+00:00",
"ETag": "W/\"datetime'2021-05-03T04%3A16%3A14.1785124Z'\""
}
メモ:プロパティに System.Text.Json.Serialization.JsonIgnore 属性を付けると、そのプロパティはJSON化の対象外にできます。
[別解] とコメントアウトしてある部分でJSON化した場合の結果は次のようになります。
要求ユニット使用量: 2
取得したエンティティ:
{"lastName":"\u5FB3\u5DDD","firstName":"\u5BB6\u5EB7","birthDay":"1843-01-31T00:00:00Z","note":"\u5E7C\u540D\u306F\u7AF9\u5343\u4EE3","PartitionKey":"\u5FB3\u5DDD","RowKey":"\u5BB6\u5EB7","Timestamp":"2021-05-03T04:16:14+00:00","ETag":"W/\u0022datetime\u00272021-05-03T04%3A16%3A14.1785124Z\u0027\u0022"}
参考
.NET Standard SDK を使用した Azure Cosmos DB Table API | Microsoft Docs
クイック スタート:.NET での Table API の使用 - Azure Cosmos DB | Microsoft Docs