

# 項目の操作: .NET
<a name="LowLevelDotNetItemCRUD"></a>

AWS SDK for .NET 低レベル API を使用して、テーブル内の項目に対して、一般的な作成、読み込み、更新、削除 (CRUD) のオペレーションを実行できます。以下に、.NET の低レベル API を使用してデータ CRUD オペレーションを実行するための一般的なステップを示します。

1. `AmazonDynamoDBClient` クラスのインスタンス（クライアント）を作成します。

1. 対応するリクエストオブジェクトで、オペレーション固有の必須パラメータを指定します。

   たとえば、項目をアップロードするときは `PutItemRequest` リクエストオブジェクトを使用し、既存の項目を取得するときは `GetItemRequest` リクエストオブジェクトを使用します。

   リクエストオブジェクトを使用して、必須パラメータとオプションパラメータの両方を指定できます。

1. 前述のステップで作成したリクエストオブジェクトを渡して、クライアントから提供された適切なメソッドを実行します。

   `AmazonDynamoDBClient` クライアントは、CRUD オペレーションに、`PutItem`、`GetItem`、`UpdateItem` および `DeleteItem` メソッドを提供します。

**Topics**
+ [項目の置換](#PutItemLowLevelAPIDotNet)
+ [項目の取得](#GetItemLowLevelDotNET)
+ [項目の更新](#UpdateItemLowLevelDotNet)
+ [アトミックカウンタ](#AtomicCounterLowLevelDotNet)
+ [項目の削除](#DeleteMidLevelDotNet)
+ [バッチ書き込み: 複数の項目の置換および削除](#BatchWriteLowLevelDotNet)
+ [バッチ取得: 複数の項目の取得](#BatchGetLowLevelDotNet)
+ [例: AWS SDK for .NET 低レベル API を使用した CRUD オペレーション](LowLevelDotNetItemsExample.md)
+ [例: AWS SDK for .NET 低レベル API を使用したバッチオペレーション](batch-operation-lowlevel-dotnet.md)
+ [例: AWS SDK for .NET 低レベル API を使用したバイナリタイプ属性の処理](LowLevelDotNetBinaryTypeExample.md)

## 項目の置換
<a name="PutItemLowLevelAPIDotNet"></a>

`PutItem` メソッドは、項目をテーブルにアップロードします。項目が存在する場合、その項目全体が置き換えられます。

**注記**  
項目全体を置き換える代わりに固有の属性のみを更新する場合は、`UpdateItem` メソッドを使用できます。詳細については、「」を参照してください[項目の更新](#UpdateItemLowLevelDotNet)

以下に、低レベル .NET SDK API を使用して項目をアップロードするステップを示します。

1. `AmazonDynamoDBClient` クラスのインスタンスを作成します。

1. `PutItemRequest` クラスのインスタンスを作成して、必要なパラメータを指定します。

   項目を配置するには、テーブル名と項目を指定する必要があります。

1. 前のステップで作成した `PutItemRequest` オブジェクトを指定して、`PutItem` メソッドを実行します。

以下の C\$1 サンプルは、前述のステップの例です。この例では、項目を `ProductCatalog` テーブルにアップロードします。

**Example**  

```
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
string tableName = "ProductCatalog";

var request = new PutItemRequest
{
   TableName = tableName,
   Item = new Dictionary<string, AttributeValue>()
      {
          { "Id", new AttributeValue { N = "201" }},
          { "Title", new AttributeValue { S = "Book 201 Title" }},
          { "ISBN", new AttributeValue { S = "11-11-11-11" }},
          { "Price", new AttributeValue { S = "20.00" }},
          {
            "Authors",
            new AttributeValue
            { SS = new List<string>{"Author1", "Author2"}   }
          }
      }
};
client.PutItem(request);
```

前の例では、`Id`、`Title`、`ISBN` および `Authors` 属性を持つブック項目をアップロードします。`Id` は数値型の属性であり、他のすべての属性は文字列型であることに注意してください。作成者は `String` セットです。

### オプションパラメータの指定
<a name="PutItemLowLevelAPIDotNetOptions"></a>

次の C\$1 例に示すように、`PutItemRequest` オブジェクトを使用してオプションのパラメータを指定することもできます。この例では、次のオプションパラメータが指定されています。
+ `ExpressionAttributeNames`、`ExpressionAttributeValues` および `ConditionExpression` は、既存の項目に特定の値を持つ ISBN 属性がある場合にのみ、項目を置き換えるように指定します。
+ レスポンスで古い項目をリクエストする `ReturnValues` パラメータ。

**Example**  

```
var request = new PutItemRequest
 {
   TableName = tableName,
   Item = new Dictionary<string, AttributeValue>()
               {
                   { "Id", new AttributeValue { N = "104" }},
                   { "Title", new AttributeValue { S = "Book 104  Title" }},
                   { "ISBN", new AttributeValue { S = "444-4444444444" }},
                   { "Authors",
                     new AttributeValue { SS = new List<string>{"Author3"}}}
               },
    // Optional parameters.
    ExpressionAttributeNames = new Dictionary<string,string>()
    {
        {"#I", "ISBN"}
    },
    ExpressionAttributeValues = new Dictionary<string, AttributeValue>()
    {
        {":isbn",new AttributeValue {S = "444-4444444444"}}
    },
    ConditionExpression = "#I = :isbn"

};
var response = client.PutItem(request);
```

詳細については、「[PutItem](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_PutItem.html)」を参照してください。

## 項目の取得
<a name="GetItemLowLevelDotNET"></a>

`GetItem` メソッドは項目を取得します。

**注記**  
複数の項目を取り出すために、`BatchGetItem` メソッドを使用できます。詳細については、「」を参照してください[バッチ取得: 複数の項目の取得](#BatchGetLowLevelDotNet)

以下に、低レベル AWS SDK for .NET API を使用して既存の項目を取得するステップを示します。

1. `AmazonDynamoDBClient` クラスのインスタンスを作成します。

1. `GetItemRequest` クラスのインスタンスを作成して、必要なパラメータを指定します。

   項目を吸いtpィするには、テーブル名と項目のプライマリキーを指定する必要があります。

1. 前のステップで作成した `GetItemRequest` オブジェクトを指定して、`GetItem` メソッドを実行します。

以下の C\$1 サンプルは、前述のステップの例です。例では、`ProductCatalog` テーブルから項目を取得します。

```
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
string tableName = "ProductCatalog";

var request = new GetItemRequest
 {
   TableName = tableName,
   Key = new Dictionary<string,AttributeValue>() { { "Id", new AttributeValue { N = "202" } } },
 };
 var response = client.GetItem(request);

// Check the response.
var result = response.GetItemResult;
var attributeMap = result.Item; // Attribute list in the response.
```

### オプションパラメータの指定
<a name="GetItemLowLevelDotNETOptions"></a>

次の C\$1 例に示すように、`GetItemRequest` オブジェクトを使用してオプションのパラメータを指定することもできます。このサンプルでは、次のオプションパラメータが指定されています。
+ 取得する属性を指定する `ProjectionExpression` パラメータ。
+ 強力な整合性のある読み込みを実行する `ConsistentRead` パラメータ。読み込み整合性の詳細については、「[DynamoDB の読み取り整合性](HowItWorks.ReadConsistency.md)」を参照してください。

**Example**  

```
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
string tableName = "ProductCatalog";

var request = new GetItemRequest
 {
   TableName = tableName,
   Key = new Dictionary<string,AttributeValue>() { { "Id", new AttributeValue { N = "202" } } },
   // Optional parameters.
   ProjectionExpression = "Id, ISBN, Title, Authors",
   ConsistentRead = true
 };

 var response = client.GetItem(request);

// Check the response.
var result = response.GetItemResult;
var attributeMap = result.Item;
```

詳細については、「[GetItem](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_GetItem.html)」を参照してください。

## 項目の更新
<a name="UpdateItemLowLevelDotNet"></a>

`UpdateItem` メソッドは、既存の項目があればそれを更新します。`UpdateItem` オペレーションを使用して、既存の属性値を更新するか、新しい属性を追加するか、既存のコレクションから属性を削除することができます。プライマリキーが指定されている項目がない場合は、新しい項目が追加されます。

`UpdateItem` オペレーションは、以下のガイドラインに従います。
+ 項目が存在しない場合、`UpdateItem` は入力で指定されたプライマリキーを使用して、新しい項目を追加します。
+ 項目が存在する場合、`UpdateItem` は次のように更新を適用します。
  + 既存の属性値を更新による値に置き換えます。
  + 入力で指定された属性が存在しない場合は、新しい属性を項目に追加します。
  + 入力された属性が null である場合は、属性を削除します。
  + `ADD` に `Action` を使用する場合は、既存のセット (文字列または数値セット) に値を追加するか、既存の数値属性値から数学的に加算 (正の数を使用) または減算 (負の数を使用) することができます。

**注記**  
`PutItem` オペレーションにより、更新を実行できます。詳細については、「」を参照してください[項目の置換](#PutItemLowLevelAPIDotNet) たとえば、`PutItem` をコールして項目をアップロードするときにプライマリキーが存在する場合は、`PutItem` オペレーションによって項目全体が置き換わります。既存の項目内に属性があり、入力でそれらの属性が指定されていない場合、それらの属性は、`PutItem` オペレーションによって削除されます。ただし、`UpdateItem` が更新するのは指定された入力属性だけです。その項目では、その他の既存の属性は変更されません。

以下に、低レベル .NET SDK API を使用して既存の項目を更新するステップを示します。

1. `AmazonDynamoDBClient` クラスのインスタンスを作成します。

1. `UpdateItemRequest` クラスのインスタンスを作成して、必要なパラメータを指定します。

   これは、属性の追加、既存の属性の更新、属性の削除など、すべての更新を記述するリクエストオブジェクトです。既存の属性を削除するには、その属性名に null 値を指定します。

1. 前のステップで作成した `UpdateItemRequest` オブジェクトを指定して、`UpdateItem` メソッドを実行します。

以下の C\$1 サンプルコードは、前述のステップの例です。例では、`ProductCatalog` テーブルのブック項目を更新します。この例では、`Authors` のコレクションに著者を追加し、既存の `ISBN` 属性を削除します。また、価格を 1 引き下げます。



```
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
string tableName = "ProductCatalog";

var request = new UpdateItemRequest
{
    TableName = tableName,
    Key = new Dictionary<string,AttributeValue>() { { "Id", new AttributeValue { N = "202" } } },
    ExpressionAttributeNames = new Dictionary<string,string>()
    {
        {"#A", "Authors"},
        {"#P", "Price"},
        {"#NA", "NewAttribute"},
        {"#I", "ISBN"}
    },
    ExpressionAttributeValues = new Dictionary<string, AttributeValue>()
    {
        {":auth",new AttributeValue { SS = {"Author YY","Author ZZ"}}},
        {":p",new AttributeValue {N = "1"}},
        {":newattr",new AttributeValue {S = "someValue"}},
    },

    // This expression does the following:
    // 1) Adds two new authors to the list
    // 2) Reduces the price
    // 3) Adds a new attribute to the item
    // 4) Removes the ISBN attribute from the item
    UpdateExpression = "ADD #A :auth SET #P = #P - :p, #NA = :newattr REMOVE #I"
};
var response = client.UpdateItem(request);
```

### オプションパラメータの指定
<a name="UpdateItemLowLevelDotNETOptions"></a>

次の C\$1 例に示すように、`UpdateItemRequest` オブジェクトを使用してオプションのパラメータを指定することもできます。次のオプションパラメータが指定されています。
+ `ExpressionAttributeValues` および `ConditionExpression` は、既存の料金が 20.00 である場合にのみ料金を更新できるように指定します。
+ レスポンスで更新された項目をリクエストする `ReturnValues` パラメータ。

**Example**  

```
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
string tableName = "ProductCatalog";

var request = new UpdateItemRequest
{
    Key = new Dictionary<string,AttributeValue>() { { "Id", new AttributeValue { N = "202" } } },

    // Update price only if the current price is 20.00.
    ExpressionAttributeNames = new Dictionary<string,string>()
    {
        {"#P", "Price"}
    },
    ExpressionAttributeValues = new Dictionary<string, AttributeValue>()
    {
        {":newprice",new AttributeValue {N = "22"}},
        {":currprice",new AttributeValue {N = "20"}}
    },
    UpdateExpression = "SET #P = :newprice",
    ConditionExpression = "#P = :currprice",
    TableName = tableName,
    ReturnValues = "ALL_NEW" // Return all the attributes of the updated item.
};

var response = client.UpdateItem(request);
```

詳細については、「[UpdateItem](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html)」を参照してください。

## アトミックカウンタ
<a name="AtomicCounterLowLevelDotNet"></a>

`updateItem` を使用してアトミックカウンターを実装できます。アトミックカウンターでは、他の書き込みリクエストを妨げることなく、既存の属性の値をインクリメントまたはデクリメントします。アトミックカウンタを更新するには、`UpdateExpression` パラメータにタイプに `Number` の属性を持つ `updateItem` および `ADD` を、`Action` として使用します。

次のサンプルはこのアトミックカウンターを示しており、`Quantity` 属性を 1 ずつインクリメントさせています。

```
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
string tableName = "ProductCatalog";

var request = new UpdateItemRequest
{
    Key = new Dictionary<string, AttributeValue>() { { "Id", new AttributeValue { N = "121" } } },
    ExpressionAttributeNames = new Dictionary<string, string>()
    {
        {"#Q", "Quantity"}
    },
    ExpressionAttributeValues = new Dictionary<string, AttributeValue>()
    {
        {":incr",new AttributeValue {N = "1"}}
    },
    UpdateExpression = "SET #Q = #Q + :incr",
    TableName = tableName
};

var response = client.UpdateItem(request);
```

## 項目の削除
<a name="DeleteMidLevelDotNet"></a>

`DeleteItem` メソッドによって、テーブルから項目を削除します。

以下では、低レベル .NET SDK API を使用して項目を削除するステップを示します。

1. `AmazonDynamoDBClient` クラスのインスタンスを作成します。

1. `DeleteItemRequest` クラスのインスタンスを作成して、必要なパラメータを指定します。

    項目を削除するには、テーブル名と項目のプライマリキーが必要です。

1. 前のステップで作成した `DeleteItemRequest` オブジェクトを指定して、`DeleteItem` メソッドを実行します。

**Example**  

```
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
string tableName = "ProductCatalog";

var request = new DeleteItemRequest
{
    TableName = tableName,
    Key = new Dictionary<string,AttributeValue>() { { "Id", new AttributeValue { N = "201" } } },
};

var response = client.DeleteItem(request);
```

### オプションパラメータの指定
<a name="DeleteItemLowLevelDotNETOptions"></a>

次の C\$1 コード例に示すように、`DeleteItemRequest` オブジェクトを使用して任意のパラメータを指定することもできます。次のオプションパラメータが指定されています。
+ `ExpressionAttributeValues` および `ConditionExpression` は、ブック項目が公開されていない場合にのみ削除できるよう指定します (InPublication 属性値は false です)。
+ レスポンスで削除された項目をリクエストする `ReturnValues` パラメータ。

**Example**  

```
var request = new DeleteItemRequest
{
    TableName = tableName,
    Key = new Dictionary<string,AttributeValue>() { { "Id", new AttributeValue { N = "201" } } },

    // Optional parameters.
    ReturnValues = "ALL_OLD",
    ExpressionAttributeNames = new Dictionary<string, string>()
    {
        {"#IP", "InPublication"}
    },
    ExpressionAttributeValues = new Dictionary<string, AttributeValue>()
    {
        {":inpub",new AttributeValue {BOOL = false}}
    },
    ConditionExpression = "#IP = :inpub"
};

var response = client.DeleteItem(request);
```

詳細については、「[DeleteItem](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DeleteItem.html)」を参照してください。

## バッチ書き込み: 複数の項目の置換および削除
<a name="BatchWriteLowLevelDotNet"></a>

*バッチ書き込み*は、複数の項目の書き込みと削除をバッチで行うことを意味します。`BatchWriteItem` メソッドによって、単一の コール内にある 1 つまたは複数のテーブルから複数の項目を置換および削除できます。以下に、低レベル .NET SDK API を使用して複数の項目を取得するステップを示します。

1. `AmazonDynamoDBClient` クラスのインスタンスを作成します。

1. `BatchWriteItemRequest` クラスのインスタンスを作成して、すべての入力および削除オペレーションを記述します。

1. 前のステップで作成した `BatchWriteItemRequest` オブジェクトを指定して、`BatchWriteItem` メソッドを実行します。

1. 応答を処理します。返された未処理のリクエスト項目が応答内に存在していたかどうかをチェックする必要があります。これは、プロビジョニングされたスループットクォータまたは他の何らかの一時的エラーに達する場合に、発生する可能性があります。また、DynamoDB によって、リクエストのサイズ、およびリクエスト内で指定できるオペレーションの数が制限されます。これらの制限を超えると、DynamoDB によってリクエストが却下されます。詳細については、[BatchWriteItem](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchWriteItem.html) を参照してください。

以下の C\$1 サンプルコードは、前述のステップの例です。この例では、`BatchWriteItemRequest` を作成して次の書き込みオペレーションを実行します。
+ `Forum` テーブル内で項目を配置します。
+ `Thread` テーブルから項目を入力および削除します。

このコードは `BatchWriteItem` を実行してバッチ操作を実行します。

```
AmazonDynamoDBClient client = new AmazonDynamoDBClient();

string table1Name = "Forum";
string table2Name = "Thread";

var request = new BatchWriteItemRequest
 {
   RequestItems = new Dictionary<string, List<WriteRequest>>
    {
      {
        table1Name, new List<WriteRequest>
        {
          new WriteRequest
          {
             PutRequest = new PutRequest
             {
                Item = new Dictionary<string,AttributeValue>
                {
                  { "Name", new AttributeValue { S = "Amazon S3 forum" } },
                  { "Threads", new AttributeValue { N = "0" }}
                }
             }
          }
        }
      } ,
      {
        table2Name, new List<WriteRequest>
        {
          new WriteRequest
          {
            PutRequest = new PutRequest
            {
               Item = new Dictionary<string,AttributeValue>
               {
                 { "ForumName", new AttributeValue { S = "Amazon S3 forum" } },
                 { "Subject", new AttributeValue { S = "My sample question" } },
                 { "Message", new AttributeValue { S = "Message Text." } },
                 { "KeywordTags", new AttributeValue { SS = new List<string> { "Amazon S3", "Bucket" }  } }
               }
            }
          },
          new WriteRequest
          {
             DeleteRequest = new DeleteRequest
             {
                Key = new Dictionary<string,AttributeValue>()
                {
                   { "ForumName", new AttributeValue { S = "Some forum name" } },
                   { "Subject", new AttributeValue { S = "Some subject" } }
                }
             }
          }
        }
      }
    }
 };
response = client.BatchWriteItem(request);
```

実例については、「[例: AWS SDK for .NET 低レベル API を使用したバッチオペレーション](batch-operation-lowlevel-dotnet.md)」を参照してください。

## バッチ取得: 複数の項目の取得
<a name="BatchGetLowLevelDotNet"></a>

`BatchGetItem` メソッドによって、1 つまたは複数のテーブルから複数の項目を取得できます。

**注記**  
単一の項目を取り出すために、`GetItem` メソッドを使用できます。

以下に、低レベル AWS SDK for .NET API を使用して複数の項目を取得するステップを示します。

1. `AmazonDynamoDBClient` クラスのインスタンスを作成します。

1. `BatchGetItemRequest` クラスのインスタンスを作成して、必要なパラメータを指定します。

   複数の項目を取得するには、テーブル名とプライマリキーバリューのリストが必要です。

1. 前のステップで作成した `BatchGetItemRequest` オブジェクトを指定して、`BatchGetItem` メソッドを実行します。

1. 応答を処理します。未処理キーがなかったかどうかを確認する必要があります。これは、プロビジョニングされたスループットクォータまたは他の何らかの一時的エラーに達する場合に発生する可能性があります。

以下の C\$1 サンプルコードは、前述のステップの例です。この例では、`Forum` および `Thread` の 2 つのテーブルから取得します。リクエストでは、`Forum` テーブルに 2 つの項目、`Thread` テーブルに 3 つの項目を指定します。応答には、両方のテーブルの項目が含まれます。このコードは、応答を処理する方法を示しています。



```
AmazonDynamoDBClient client = new AmazonDynamoDBClient();

string table1Name = "Forum";
string table2Name = "Thread";

var request = new BatchGetItemRequest
{
  RequestItems = new Dictionary<string, KeysAndAttributes>()
  {
    { table1Name,
      new KeysAndAttributes
      {
        Keys = new List<Dictionary<string, AttributeValue>>()
        {
          new Dictionary<string, AttributeValue>()
          {
            { "Name", new AttributeValue { S = "DynamoDB" } }
          },
          new Dictionary<string, AttributeValue>()
          {
            { "Name", new AttributeValue { S = "Amazon S3" } }
          }
        }
      }
    },
    {
      table2Name,
      new KeysAndAttributes
      {
        Keys = new List<Dictionary<string, AttributeValue>>()
        {
          new Dictionary<string, AttributeValue>()
          {
            { "ForumName", new AttributeValue { S = "DynamoDB" } },
            { "Subject", new AttributeValue { S = "DynamoDB Thread 1" } }
          },
          new Dictionary<string, AttributeValue>()
          {
            { "ForumName", new AttributeValue { S = "DynamoDB" } },
            { "Subject", new AttributeValue { S = "DynamoDB Thread 2" } }
          },
          new Dictionary<string, AttributeValue>()
          {
            { "ForumName", new AttributeValue { S = "Amazon S3" } },
            { "Subject", new AttributeValue { S = "Amazon S3 Thread 1" } }
          }
        }
      }
    }
  }
};

var response = client.BatchGetItem(request);

// Check the response.
var result = response.BatchGetItemResult;
var responses = result.Responses; // The attribute list in the response.

var table1Results = responses[table1Name];
Console.WriteLine("Items in table {0}" + table1Name);
foreach (var item1 in table1Results.Items)
{
  PrintItem(item1);
}

var table2Results = responses[table2Name];
Console.WriteLine("Items in table {1}" + table2Name);
foreach (var item2 in table2Results.Items)
{
  PrintItem(item2);
}
// Any unprocessed keys? could happen if you exceed ProvisionedThroughput or some other error.
Dictionary<string, KeysAndAttributes> unprocessedKeys = result.UnprocessedKeys;
foreach (KeyValuePair<string, KeysAndAttributes> pair in unprocessedKeys)
{
    Console.WriteLine(pair.Key, pair.Value);
}
```



### オプションパラメータの指定
<a name="BatchGetItemLowLevelDotNETOptions"></a>

次の C\$1 コード例に示すように、`BatchGetItemRequest` オブジェクトを使用して任意のパラメータを指定することもできます。例では、`Forum` テーブルから 2 つの項目を取得します。次のオプションパラメータが指定されています。
+  取得する属性を指定する `ProjectionExpression` パラメータ。

**Example**  

```
AmazonDynamoDBClient client = new AmazonDynamoDBClient();

string table1Name = "Forum";

var request = new BatchGetItemRequest
{
  RequestItems = new Dictionary<string, KeysAndAttributes>()
  {
    { table1Name,
      new KeysAndAttributes
      {
        Keys = new List<Dictionary<string, AttributeValue>>()
        {
          new Dictionary<string, AttributeValue>()
          {
            { "Name", new AttributeValue { S = "DynamoDB" } }
          },
          new Dictionary<string, AttributeValue>()
          {
            { "Name", new AttributeValue { S = "Amazon S3" } }
          }
        }
      },
      // Optional - name of an attribute to retrieve.
      ProjectionExpression = "Title"
    }
  }
};

var response = client.BatchGetItem(request);
```

詳細については、[BatchGetItem](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchGetItem.html) を参照してください。