

# Trabalhar com itens: .NET
<a name="LowLevelDotNetItemCRUD"></a>

Você pode usar a API de baixo nível do AWS SDK para .NET para executar operações típicas create, read, update, delete (CRUD - criação, leitura, atualização e exclusão) em um item de uma tabela. Veja a seguir as etapas comuns que você segue para executar operações CRUD em dados usando a API de baixo nível do .NET:

1. Crie uma instância da classe `AmazonDynamoDBClient` (o cliente).

1. Forneça os parâmetros necessários específicos à operação em um objeto de solicitação correspondente.

   Por exemplo, use o objeto de solicitação `PutItemRequest` ao carregar um item e use o objeto de solicitação `GetItemRequest` ao recuperar um item existente. 

   Você pode usar o objeto de solicitação para fornecer tanto parâmetros necessários quanto opcionais. 

1. Execute o método apropriado fornecido pelo cliente, transmitindo o objeto de solicitação que você criou na etapa anterior. 

   O cliente `AmazonDynamoDBClient` fornece os métodos `PutItem`, `GetItem`, `UpdateItem` e `DeleteItem` para as operações CRUD.

**Topics**
+ [Colocar um item](#PutItemLowLevelAPIDotNet)
+ [Obter um item](#GetItemLowLevelDotNET)
+ [Atualizar um item](#UpdateItemLowLevelDotNet)
+ [Contador atômico](#AtomicCounterLowLevelDotNet)
+ [Excluir um item](#DeleteMidLevelDotNet)
+ [Gravação em lote: colocar e excluir vários itens](#BatchWriteLowLevelDotNet)
+ [Obtenção em lote: obter vários itens](#BatchGetLowLevelDotNet)
+ [Exemplo: operações CRUD usando a API de baixo nível AWS SDK para .NET](LowLevelDotNetItemsExample.md)
+ [Exemplo: operações em lote usando a API de baixo nível do AWS SDK para .NET](batch-operation-lowlevel-dotnet.md)
+ [Exemplo: tratar atributos do tipo binário usando a API de baixo nível do AWS SDK para .NET](LowLevelDotNetBinaryTypeExample.md)

## Colocar um item
<a name="PutItemLowLevelAPIDotNet"></a>

O método `PutItem` carrega um item em uma tabela. Se o item existe, ele substitui o item inteiro.

**nota**  
Em vez de substituir o item inteiro, se você quiser atualizar apenas atributos específicos, use o método `UpdateItem`. Para obter mais informações, consulte [Atualizar um item](#UpdateItemLowLevelDotNet).

Veja a seguir as etapas para carregar um item usando a API do SDK do .NET de baixo nível:

1. Crie uma instância da classe `AmazonDynamoDBClient`.

1. Forneça os parâmetros necessários, criando uma instância da classe `PutItemRequest`.

   Para inserir item, você deve fornecer o nome da tabela e o item. 

1. Execute o método `PutItem` fornecendo o objeto `PutItemRequest` que você criou na etapa anterior.

O exemplo de C\$1 a seguir demonstra as etapas anteriores. O exemplo faz upload de um item para a tabela `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);
```

No exemplo anterior, você faz upload de um item de livro que tem os atributos `Id`, `Title`, `ISBN` e `Authors`. Observe que `Id` é um atributo de tipo numérico, e todos os outros atributos são do tipo string. Autores é um conjunto `String`.

### Especificar parâmetros opcionais
<a name="PutItemLowLevelAPIDotNetOptions"></a>

Você também pode fornecer parâmetros opcionais usando o objeto `PutItemRequest`, conforme mostrado no seguinte exemplo de C\$1. O exemplo especifica os seguintes parâmetros opcionais:
+ `ExpressionAttributeNames`, `ExpressionAttributeValues` e `ConditionExpression` especificam que o item pode ser substituído somente se o item existente tiver o atributo ISBN com um valor específico.
+ `ReturnValues`o parâmetro para solicitar o item antigo na resposta.

**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);
```

Para obter mais informações, consulte [PutItem](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_PutItem.html).

## Obter um item
<a name="GetItemLowLevelDotNET"></a>

O método `GetItem` recupera um item.

**nota**  
Para recuperar vários itens, você pode usar o método `BatchGetItem`. Para obter mais informações, consulte [Obtenção em lote: obter vários itens](#BatchGetLowLevelDotNet).

Veja a seguir as etapas para recuperar um item existente usando a API do AWS SDK para .NET de baixo nível.

1. Crie uma instância da classe `AmazonDynamoDBClient`.

1. Forneça os parâmetros necessários, criando uma instância da classe `GetItemRequest`.

   Para obter um item, você deve fornecer o nome da tabela e a chave primária desse item. 

1. Execute o método `GetItem` fornecendo o objeto `GetItemRequest` que você criou na etapa anterior.

O exemplo de C\$1 a seguir demonstra as etapas anteriores. O exemplo recupera um item da tabela `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.
```

### Especificar parâmetros opcionais
<a name="GetItemLowLevelDotNETOptions"></a>

Você também pode fornecer parâmetros opcionais usando o objeto `GetItemRequest`, conforme mostrado no seguinte exemplo de C\$1. O exemplo especifica os parâmetros opcionais a seguir:
+ `ProjectionExpression`o parâmetro para especificar os atributos a serem recuperados.
+ `ConsistentRead`o parâmetro para realizar uma leitura fortemente consistente. Para saber mais sobre a consistência de leitura, consulte [Consistência de leitura do 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;
```

Para obter mais informações, consulte [GetItem](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_GetItem.html).

## Atualizar um item
<a name="UpdateItemLowLevelDotNet"></a>

O método `UpdateItem` atualiza um item existente, se estiver presente. É possível usar a operação `UpdateItem` para atualizar valores de atributos existentes, adicionar novos atributos ou excluir atributos da coleção existente. Se o item que tem a chave primária especificada não for encontrado, ela adicionará um novo item.

A operação `UpdateItem` usa as seguintes diretrizes:
+ Se o item não existir, o `UpdateItem` adicionará um novo item usando a chave primária especificada na entrada.
+ Se o item existir, o `UpdateItem` aplicará as atualizações da seguinte maneira:
  + Substitui os valores de atributos existentes pelos valores na atualização.
  + Se o atributo que você fornecer na entrada não existir, ele adicionará um novo atributo ao item.
  + Se o valor do atributo de entrada for nulo, ele excluirá o atributo, se estiver presente. 
  + Se você usar `ADD` para a `Action`, poderá adicionar valores a um conjunto existente (conjunto de strings ou números) ou adicionar (usar um número positivo) ou subtrair (usar um número negativo) matematicamente com base no valor de atributo numérico existente.

**nota**  
A operação `PutItem` também pode realizar uma atualização. Para obter mais informações, consulte [Colocar um item](#PutItemLowLevelAPIDotNet). Por exemplo, se você chamar `PutItem` para fazer upload de um item, e a chave primária existir, a operação `PutItem` substituirá o item inteiro. Se houver atributos no item existente e esses atributos não forem especificados na entrada, a operação `PutItem` os excluirá. No entanto, `UpdateItem` só atualiza os atributos de entrada especificados. Outros atributos existentes desse item permanecerão inalterados. 

Veja a seguir as etapas para atualizar um item existente usando a API do SDK do .NET de baixo nível:

1. Crie uma instância da classe `AmazonDynamoDBClient`.

1. Forneça os parâmetros necessários, criando uma instância da classe `UpdateItemRequest`.

   Este é o objeto de solicitação em que você descreve todas as atualizações, por exemplo, adiciona atributos, atualizar atributos existentes ou excluir atributos. Para excluir um atributo existente, especifique o nome desse atributo com um valor nulo. 

1. Execute o método `UpdateItem` fornecendo o objeto `UpdateItemRequest` que você criou na etapa anterior. 

O exemplo de código C\$1 a seguir demonstra as etapas anteriores. O exemplo de código atualiza um item na tabela `ProductCatalog`. Ele adiciona um novo autor à coleção `Authors` e exclui o atributo `ISBN` existente. Ele também reduz o preço por um.



```
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);
```

### Especificar parâmetros opcionais
<a name="UpdateItemLowLevelDotNETOptions"></a>

Você também pode fornecer parâmetros opcionais usando o objeto `UpdateItemRequest`, conforme mostrado no seguinte exemplo de C\$1. Especifica os parâmetros opcionais a seguir:
+ `ExpressionAttributeValues` e `ConditionExpression` para especificar que o preço apenas poderá ser atualizado se o preço existente for 20,00.
+ `ReturnValues`o parâmetro para solicitar o item atualizado na resposta. 

**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);
```

Para obter mais informações, consulte [UpdateItem](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html). 

## Contador atômico
<a name="AtomicCounterLowLevelDotNet"></a>

Você pode usar `updateItem` para implementar um contador atômico, onde pode aumentar ou reduzir o valor de um atributo existente sem interferir em outras solicitações de gravação. Para atualizar um contador atômico, use `updateItem` com um atributo do tipo `Number` no parâmetro `UpdateExpression` e `ADD` como a `Action`.

O exemplo de código a seguir demonstra isso incrementando o atributo `Quantity` em um.

```
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);
```

## Excluir um item
<a name="DeleteMidLevelDotNet"></a>

O método `DeleteItem` exclui um item de uma tabela. 

Veja a seguir as etapas para excluir um item usando a API de SDK do .NET de baixo nível. 

1. Crie uma instância da classe `AmazonDynamoDBClient`.

1. Forneça os parâmetros necessários, criando uma instância da classe `DeleteItemRequest`.

    Para excluir um item, o nome da tabela e a chave primária desse item são necessários. 

1. Execute o método `DeleteItem` fornecendo o objeto `DeleteItemRequest` que você criou na etapa anterior. 

**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);
```

### Especificar parâmetros opcionais
<a name="DeleteItemLowLevelDotNETOptions"></a>

Você também pode fornecer parâmetros opcionais usando o objeto `DeleteItemRequest`, conforme mostrado no seguinte exemplo de código C\$1. Especifica os parâmetros opcionais a seguir:
+ `ExpressionAttributeValues` e `ConditionExpression` para especificar que o item de livro apenas poderá ser excluído se não estiver mais em publicação (se o valor do atributo InPublication for false). 
+ `ReturnValues`o parâmetro para solicitar o item excluído na resposta.

**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);
```

Para obter mais informações, consulte [DeleteItem](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DeleteItem.html).

## Gravação em lote: colocar e excluir vários itens
<a name="BatchWriteLowLevelDotNet"></a>

*Gravação em lote* se refere a inserir e excluir vários itens em um lote. O método `BatchWriteItem` permite que você insira e exclua vários itens de uma ou mais tabelas em uma única chamada. Veja a seguir as etapas para recuperar vários itens usando a API de SDK do .NET de baixo nível.

1. Crie uma instância da classe `AmazonDynamoDBClient`.

1. Descreva todas as operações de inserção e exclusão, criando uma instância da classe `BatchWriteItemRequest`.

1. Execute o método `BatchWriteItem` fornecendo o objeto `BatchWriteItemRequest` que você criou na etapa anterior.

1. Processe a resposta. Você deve verificar se há itens de solicitação não processados retornados na resposta. Isso poderá acontecer se você atingir a cota de throughput provisionado ou por algum outro erro temporário. Além disso, o DynamoDB limita o tamanho da solicitação e o número de operações que você pode especificar em uma solicitação. Se você exceder esses limites, o DynamoDB rejeitará a solicitação. Para obter mais informações, consulte [BatchWriteItem](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchWriteItem.html). 

O exemplo de código C\$1 a seguir demonstra as etapas anteriores. O exemplo cria uma `BatchWriteItemRequest` para realizar as seguintes operações de gravação:
+ Inserir um item na tabela `Forum`.
+ Inserir e excluir um item da tabela `Thread`.

Em seguida, o código executa `BatchWriteItem` para realizar uma operação em lote.

```
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);
```

Para obter um exemplo funcional, consulte [Exemplo: operações em lote usando a API de baixo nível do AWS SDK para .NET](batch-operation-lowlevel-dotnet.md). 

## Obtenção em lote: obter vários itens
<a name="BatchGetLowLevelDotNet"></a>

O método `BatchGetItem` permite que você recupere vários itens de uma ou mais tabelas. 

**nota**  
Para recuperar um único item, você pode usar o método `GetItem`. 

Veja a seguir as etapas para recuperar vários itens usando a API do AWS SDK para .NET de baixo nível.

1. Crie uma instância da classe `AmazonDynamoDBClient`.

1. Forneça os parâmetros necessários, criando uma instância da classe `BatchGetItemRequest`.

   Para recuperar vários itens, o nome da tabela e uma lista de valores de chave primária são necessários. 

1. Execute o método `BatchGetItem` fornecendo o objeto `BatchGetItemRequest` que você criou na etapa anterior.

1. Processe a resposta. Você deve verificar se houve chaves não processadas, o que pode acontecer caso você tenha atingido a cota de throughput provisionado ou caso tenha ocorrido algum outro erro temporário.

O exemplo de código C\$1 a seguir demonstra as etapas anteriores. O exemplo recupera itens de duas tabelas, `Forum` e `Thread`. A solicitação especifica dois itens na tabela `Forum` e três itens em `Thread`. A resposta inclui itens de ambas as tabelas. O código mostra como você pode processar a resposta.



```
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);
}
```



### Especificar parâmetros opcionais
<a name="BatchGetItemLowLevelDotNETOptions"></a>

Você também pode fornecer parâmetros opcionais usando o objeto `BatchGetItemRequest`, conforme mostrado no seguinte exemplo de código C\$1. O exemplo recupera dois itens da tabela `Forum`. Ele especifica o parâmetro opcional a seguir:
+  `ProjectionExpression`o parâmetro para especificar os atributos a serem recuperados.

**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);
```

Para obter mais informações, consulte [BatchGetItem](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchGetItem.html). 