

 适用于 .NET 的 AWS SDK V3 已进入维护模式。

我们建议您迁移到 [适用于 .NET 的 AWS SDK V4](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/welcome.html)。有关如何迁移的更多详细信息和信息，请参阅我们的[维护模式公告](https://aws.amazon.com/blogs/developer/aws-sdk-for-net-v3-maintenance-mode-announcement/)。

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用 Amazon DynamoDB NoSQL 数据库
<a name="dynamodb-intro"></a>

**注意**  
这些主题中的编程模型同时存在于 .NET Framework 和 .NET (Core) 中，但是调用约定不同，无论是同步还是异步。

 适用于 .NET 的 AWS SDK 支持 Amazon DynamoDB，这是一项由提供的快速 NoSQL 数据库服务。 AWS开发工具包为与 DynamoDB 通信提供了三种编程模型：*低级*模型、*文档*模型和*对象持久性*模型。

以下信息介绍了这些模型及其模型 APIs，提供了如何以及何时使用它们的示例，并提供了指向中其他 DynamoDB 编程资源的链接。 适用于 .NET 的 AWS SDK

## 低级模型
<a name="dynamodb-intro-apis-low-level"></a>

低级编程模型封装对 DynamoDB 服务的直接调用。您可以通过 [Amazon.Dynamo DBv2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/DynamoDBv2/NDynamoDBv2.html) 命名空间访问此模型。

在三种模型中，低级模型需要编写的代码最多。例如，您必须将 .NET 数据类型转换为 DynamoDB 中的对等类型。但是，此模型向您提供了对大部分功能的访问。

以下示例显示如何使用低级模型创建表、修改表以及将项目插入到 DynamoDB 中的表。

### 创建表
<a name="dynamodb-intro-apis-low-level-create-table"></a>

在以下示例中，您可以使用 `CreateTable` 类的 `AmazonDynamoDBClient` 方法创建表。`CreateTable` 方法使用包含特性的 `CreateTableRequest` 类的实例，例如必需的项目属性名称、主键定义和吞吐容量。该 `CreateTable` 方法返回 `CreateTableResponse` 类的实例。

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();

Console.WriteLine("Getting list of tables");
List<string> currentTables = client.ListTables().TableNames;
Console.WriteLine("Number of tables: " + currentTables.Count);
if (!currentTables.Contains("AnimalsInventory"))
{
    var request = new CreateTableRequest
    {
        TableName = "AnimalsInventory",
        AttributeDefinitions = new List<AttributeDefinition>
      {
        new AttributeDefinition
        {
          AttributeName = "Id",
          // "S" = string, "N" = number, and so on.
          AttributeType = "N"
        },
        new AttributeDefinition
        {
          AttributeName = "Type",
          AttributeType = "S"
        }
      },
        KeySchema = new List<KeySchemaElement>
      {
        new KeySchemaElement
        {
          AttributeName = "Id",
          // "HASH" = hash key, "RANGE" = range key.
          KeyType = "HASH"
        },
        new KeySchemaElement
        {
          AttributeName = "Type",
          KeyType = "RANGE"
        },
      },
        ProvisionedThroughput = new ProvisionedThroughput
        {
            ReadCapacityUnits = 10,
            WriteCapacityUnits = 5
        },
    };

    var response = client.CreateTable(request);

    Console.WriteLine("Table created with request ID: " +
      response.ResponseMetadata.RequestId);
}
```

### 验证该表已准备好修改
<a name="dynamodb-intro-apis-low-level-verify-table"></a>

您必须先准备好表进行修改，然后才能更改或修改表。以下示例显示了如何使用低级模型验证 DynamoDB 中的表已准备就绪。在此示例中，通过 `DescribeTable` 类的 `AmazonDynamoDBClient` 方法引用要检查的目标表。该代码每五秒检查一次表的 `TableStatus` 属性的值。当状态设置为 `ACTIVE` 时，表已准备好供修改。

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();      
var status = "";

do
{
  // Wait 5 seconds before checking (again).
  System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));
        
  try
  {
    var response = client.DescribeTable(new DescribeTableRequest
    {
      TableName = "AnimalsInventory"
    });

    Console.WriteLine("Table = {0}, Status = {1}",
      response.Table.TableName,
      response.Table.TableStatus);

    status = response.Table.TableStatus;
  }
  catch (ResourceNotFoundException)
  {
    // DescribeTable is eventually consistent. So you might
    //   get resource not found. 
  }

} while (status != TableStatus.ACTIVE);
```

### 将项目插入到表中
<a name="dynamodb-intro-apis-low-level-insert-item"></a>

在以下示例中，您使用低级模型将两个项目插入到 DynamoDB 中的表。每个项目通过 `PutItem` 类的 `AmazonDynamoDBClient` 方法插入，使用 `PutItemRequest` 类的实例。`PutItemRequest` 类的两个实例中的每个实例都接受将要插入项目的表名以及一系列项目属性值。

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();

var request1 = new PutItemRequest
{
  TableName = "AnimalsInventory",
  Item = new Dictionary<string, AttributeValue>
  {
    { "Id", new AttributeValue { N = "1" }},
    { "Type", new AttributeValue { S = "Dog" }},
    { "Name", new AttributeValue { S = "Fido" }}
  }
};

var request2 = new PutItemRequest
{
  TableName = "AnimalsInventory",
  Item = new Dictionary<string, AttributeValue>
  {
    { "Id", new AttributeValue { N = "2" }},
    { "Type", new AttributeValue { S = "Cat" }},
    { "Name", new AttributeValue { S = "Patches" }}
  }
};
        
client.PutItem(request1);
client.PutItem(request2);
```

## 文档模型
<a name="dynamodb-intro-apis-document"></a>

文档编程模型提供了一种更简单的方法来处理 DynamoDB 中的数据。此模型专门用于访问表和表中的项目。您可以通过 [Amazon. DBv2 Dynamo 访问此模型。 DocumentModel](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/DynamoDBv2/NDynamoDBv2DocumentModel.html)命名空间。

与低级编程模型相比，使用文档模型更容易针对 DynamoDB 数据编写代码。例如，您无需将相同数量的 .NET 数据类型转换为 DynamoDB 中的对等类型。不过，使用此模型所能访问的功能没有低级编程模型所提供的多。例如，您可以使用此模型创建、检索、更新和删除表中的项目。但是，要创建表，您必须使用低级模型。与对象持久化模型相比，此模型需要编写更多代码来存储、加载和查询 .NET 对象。

有关 DynamoDB 文档编程模型的更多信息，请参阅 [Amazon DynamoDB 开发人员指南](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/)中的 [.NET：文档模型](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DotNetSDKMidLevel.html)。

以下各节提供有关如何创建所需的 DynamoDB 表的表示形式的信息，以及如何使用文档模型将项目插入表和从表中获取项目的示例。

### 创建表的表示形式
<a name="dynamodb-intro-apis-document-table"></a>

要使用文档模型执行数据操作，您必须首先创建 `Table` 类的实例，它会代表特定的表。有两种主要方式可执行此操作：

**LoadTable method**

第一种机制是使用 [https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/DynamoDBv2/TTable.html](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/DynamoDBv2/TTable.html) 类的静态 `LoadTable` 方法之一，类似于以下示例：

```
var client = new AmazonDynamoDBClient();
Table table = Table.LoadTable(client, "Reply");
```

**注意**  
虽然这种机制起作用，但在某些条件下，由于冷启动和线程池行为，它有时会导致额外的延迟或死锁。有关这些行为的更多信息，请参阅博客文章 [Improved DynamoDB Initialization Patterns for the 适用于 .NET 的 AWS SDK](https://aws.amazon.com/blogs/developer/improved-dynamodb-initialization-patterns-for-the-aws-sdk-for-net/)。

**TableBuilder**

[ AWSSDK. DBv2 NuGet Dynamo 软件包的 3.7.203 版本中引入了另一种机制，即[https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/DynamoDBv2/TTableBuilder.html](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/DynamoDBv2/TTableBuilder.html)](https://www.nuget.org/packages/AWSSDK.DynamoDBv2/3.7.203)类。该机制可以通过删除某些隐式方法调用（特别是 `DescribeTable` 方法）来解决上述行为。此机制的使用方式类似于以下示例：

```
var client = new AmazonDynamoDBClient();
var table = new TableBuilder(client, "Reply")
    .AddHashKey("Id", DynamoDBEntryType.String)
    .AddRangeKey("ReplyDateTime", DynamoDBEntryType.String)
    .AddGlobalSecondaryIndex("PostedBy-Message-index", "Author", DynamoDBEntryType.String, "Message", DynamoDBEntryType.String)
    .Build();
```

有关此替代机制的更多信息，请再次参阅博客文章 [Improved DynamoDB Initialization Patterns for the 适用于 .NET 的 AWS SDK](https://aws.amazon.com/blogs/developer/improved-dynamodb-initialization-patterns-for-the-aws-sdk-for-net/)。

### 将项目插入到表中
<a name="dynamodb-intro-apis-document-insert-item"></a>

在以下示例中，回复通过 `Table` 类的 `PutItemAsync` 方法插入到 Reply 表中。`PutItemAsync` 方法获取 `Document` 类的实例；`Document` 类只是已初始化属性的集合。

```
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DocumentModel;

// Create a representation of the "Reply" table
//  by using one of the mechanisms described previously.

// Then, add a reply to the table.
var newReply = new Document();
newReply["Id"] = Guid.NewGuid().ToString();
newReply["ReplyDateTime"] = DateTime.UtcNow;
newReply["PostedBy"] = "Author1";
newReply["Message"] = "Thank you!";

await table.PutItemAsync(newReply);
```

### 从表中获取项目
<a name="dynamodb-intro-apis-document-get-item"></a>

在以下示例中，通过 `Table` 类的 `GetItemAsync` 方法检索回复。为了确定要获得的回复，该`GetItemAsync`方法使用目标回复 hash-and-range的主键。

```
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DocumentModel;

// Create a representation of the "Reply" table
//  by using one of the mechanisms described previously.

// Then, get a reply from the table
//  where "guid" is the hash key and "datetime" is the range key.
var reply = await table.GetItemAsync(guid, datetime);
Console.WriteLine("Id = " + reply["Id"]);
Console.WriteLine("ReplyDateTime = " + reply["ReplyDateTime"]);
Console.WriteLine("PostedBy = " + reply["PostedBy"]);
Console.WriteLine("Message = " + reply["Message"]);
```

前面的示例为 `WriteLine` 方法隐式将表值转换为字符串。您可以使用 `DynamoDBEntry` 类的多种“As[type]”方法执行显式转换。例如，对于 `Id` 的值，您可以通过 `AsGuid()` 方法将其从 `Primitive` 数据类型显式转换为 GUID：

```
var guid = reply["Id"].AsGuid();
```

## 对象持久化模型
<a name="dynamodb-intro-apis-object-persistence"></a>

对象持久性编程模型专门针对在 DynamoDB 中存储、加载和查询 .NET 对象而设计。您可以通过 [Amazon. DBv2 Dynamo 访问此模型。 DataModel](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/DynamoDBv2/NDynamoDBv2DataModel.html)命名空间。

在三种模型中，使用对象持久性模型最容易针对要存储、加载或查询的 DynamoDB 数据编写代码。例如，您可以直接使用 DynamoDB 数据类型。但是，此模型仅支持在 DynamoDB 中存储、加载和查询 .NET 对象的操作。例如，您可以使用此模型创建、检索、更新和删除表中的项目。不过，您必须先使用低级模型创建表，然后使用此模型将 .NET 类映射到表。

有关 DynamoDB 对象持久性编程模型的更多信息，请参阅 [Amazon DynamoDB 开发人员指南](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/)中的 [.NET：对象持久性模型](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DotNetSDKHighLevel.html)。

以下示例向您演示如何定义表示 DynamoDB 项目的 .NET 类，使用 .NET 类的实例将项目插入到 DynamoDB ，以及使用 .NET 对象的实例从表获取项目。

### 定义表示表中项目的 .NET 类
<a name="dynamodb-intro-apis-object-persistence-net-class-item"></a>

在下面的类定义示例中，`DynamoDBTable`属性指定表名，而`DynamoDBHashKey`和`DynamoDBRangeKey`属性则建模表 hash-and-range的主键。定义 `DynamoDBGlobalSecondaryIndexHashKey` 属性的目的是为了可以构造对特定作者回复的查询。

```
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;

[DynamoDBTable("Reply")]
public class Reply
{
    [DynamoDBHashKey]
    public string Id { get; set; }

    [DynamoDBRangeKey(StoreAsEpoch = false)]
    public DateTime ReplyDateTime { get; set; }

    [DynamoDBGlobalSecondaryIndexHashKey("PostedBy-Message-Index",
        AttributeName ="PostedBy")]
    public string Author { get; set; }

    [DynamoDBGlobalSecondaryIndexRangeKey("PostedBy-Message-Index")]
    public string Message { get; set; }
}
```

### 为对象持久性模型创建上下文
<a name="dynamodb-intro-apis-object-persistence-context"></a>

要使用适用于 DynamoDB 的对象持久性编程模型，您需要创建一个上下文，它提供到 DynamoDB 的连接，让您能够访问表、执行各种操作，以及执行查询。

**基本上下文**

以下代码示例演示如何创建最基本的上下文 。

```
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;

var client = new AmazonDynamoDBClient();
var context = new DynamoDBContext(client);
```

**与 DisableFetchingTableMetadata 属性的上下文**

以下示例显示了如何额外设置 `DynamoDBContextConfig` 类的 `DisableFetchingTableMetadata` 属性以防止隐式调用 `DescribeTable` 方法。

```
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;

var client = new AmazonDynamoDBClient();
var context = new DynamoDBContext(client, new DynamoDBContextConfig
{
    DisableFetchingTableMetadata = true
});
```

如果将该 `DisableFetchingTableMetadata` 属性设置为 `false`（默认值），如第一个示例所示，则可以省略 `Reply` 类中描述表项键和索引结构的属性。相反，这些属性将通过对 `DescribeTable` 方法的隐式调用推断出来。如第二个示例所示，如果 `DisableFetchingTableMetadata` 设置为 `true`，则对象持久性模型的方法（例如 `SaveAsync` 和 `QueryAsync`）完全依赖于 `Reply` 类中定义的属性。在这种情况下，不会调用 `DescribeTable` 方法。

**注意**  
在某些情况下，由于冷启动和线程池行为，对 `DescribeTable` 方法的调用有时会导致额外的延迟或死锁。因此，有时避免调用该方法是有利的。  
有关这些行为的更多信息，请参阅博客文章 [Improved DynamoDB Initialization Patterns for the 适用于 .NET 的 AWS SDK](https://aws.amazon.com/blogs/developer/improved-dynamodb-initialization-patterns-for-the-aws-sdk-for-net/)。

### 使用 .NET 类的实例将项目插入到表中
<a name="dynamodb-intro-apis-object-persistence-net-insert-item"></a>

在本示例中，项目通过 `SaveAsync` 类的 `DynamoDBContext` 方法插入，该方法采用表示项目的 .NET 类的已初始化实例。

```
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;

// Create an appropriate context for the object persistence programming model,
//  examples of which have been described earlier.

// Create an object that represents the new item.
var reply = new Reply()
{
    Id = Guid.NewGuid().ToString(),
    ReplyDateTime = DateTime.UtcNow,
    Author = "Author1",
    Message = "Thank you!"
};

// Insert the item into the table.
await context.SaveAsync<Reply>(reply, new DynamoDBOperationConfig
{
    IndexName = "PostedBy-Message-index"
});
```

### 使用 .NET 类的实例从表中获取项目
<a name="dynamodb-intro-apis-object-persistence-net-get-item"></a>

在此示例中，使用 `DynamoDBContext` 类的 `QueryAsync` 方法创建了一个查询，用于查找“Author1”的所有记录。然后，通过查询的 `GetNextSetAsync` 方法检索项目。

```
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;

// Create an appropriate context for the object persistence programming model,
//  examples of which have been described earlier.

// Construct a query that finds all replies by a specific author.
var query = context.QueryAsync<Reply>("Author1", new DynamoDBOperationConfig
{
    IndexName = "PostedBy-Message-index"
});

// Display the result.
var set = await query.GetNextSetAsync();
foreach (var item in set)
{
    Console.WriteLine("Id = " + item.Id);
    Console.WriteLine("ReplyDateTime = " + item.ReplyDateTime);
    Console.WriteLine("PostedBy = " + item.Author);
    Console.WriteLine("Message = " + item.Message);
}
```

### 有关对象持久性模型的其它信息
<a name="dynamodb-intro-apis-object-persistence-more-into"></a>

上面显示的示例和解释有时包括名为 `DisableFetchingTableMetadata` 的 `DynamoDBContext` 类的属性。此属性是在 [ AWSSDK.Dynamo DBv2 NuGet 包的 3.7.203 版本](https://www.nuget.org/packages/AWSSDK.DynamoDBv2/3.7.203)中引入的，允许您避免某些可能由于冷启动和线程池行为而导致额外延迟或死锁的情况。有关更多信息，请参阅博客文章 [Improved DynamoDB Initialization Patterns for the 适用于 .NET 的 AWS SDK](https://aws.amazon.com/blogs/developer/improved-dynamodb-initialization-patterns-for-the-aws-sdk-for-net/)。

以下是有关此属性的一些其它信息。
+ 如果您使用.NET Framework，则可以在 `app.config` 或 `web.config` 文件中全局设置此属性。
+ 可以使用 [https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/Amazon/TAWSConfigsDynamoDB.html](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/Amazon/TAWSConfigsDynamoDB.html) 类全局设置此属性，如下面的示例所示。

  ```
  // Set the DisableFetchingTableMetadata property globally
  // before constructing any context objects.
  AWSConfigsDynamoDB.Context.DisableFetchingTableMetadata = true;
  
  var client = new AmazonDynamoDBClient();
  var context = new DynamoDBContext(client);
  ```
+ 在某些情况下，您无法将 DynamoDB 属性添加到 .NET 类中；例如，如果该类是在依赖项中定义的。在这种情况下，仍然可以利用 `DisableFetchingTableMetadata` 属性。为此，除了 `DisableFetchingTableMetadata` 属性之外，还要使用 [https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/DynamoDBv2/TTableBuilder.html](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/DynamoDBv2/TTableBuilder.html) 类。该`TableBuilder`类也是在 [ AWSSDK.Dynamo 软件包的 3.7.203 版本中引入的。DBv2 NuGet ](https://www.nuget.org/packages/AWSSDK.DynamoDBv2/3.7.203)

  ```
  // Set the DisableFetchingTableMetadata property globally
  // before constructing any context objects.
  AWSConfigsDynamoDB.Context.DisableFetchingTableMetadata = true;
  
  var client = new AmazonDynamoDBClient();
  var context = new DynamoDBContext(client);
  
  var table = new TableBuilder(client, "Reply")
      .AddHashKey("Id", DynamoDBEntryType.String)
      .AddRangeKey("ReplyDateTime", DynamoDBEntryType.String)
      .AddGlobalSecondaryIndex("PostedBy-Message-index", "Author", DynamoDBEntryType.String,
          "Message", DynamoDBEntryType.String)
      .Build();
  
  // This registers the "Reply" table we constructed via the builder.
  context.RegisterTableDefinition(table);
  
  // Now operations like this will work,
  // even if the Reply class was not annotated with this index.
  var query = context.QueryAsync<Reply>("Author1", new DynamoDBOperationConfig()
  {
      IndexName = "PostedBy-Message-index"
  });
  ```

## 更多信息
<a name="dynamodb-intro-more-info"></a>

 **使用编程 DynamoDB、信息和示例 适用于 .NET 的 AWS SDK **
+  [DynamoDB APIs](http://blogs.aws.amazon.com/net/post/Tx17SQHVEMW8MXC/DynamoDB-APIs) 
+  [DynamoDB 系列入门](http://blogs.aws.amazon.com/net/post/Tx2XQOCY08QMTKO/DynamoDB-Series-Kickoff) 
+  [DynamoDB 系列 - 文档模型](http://blogs.aws.amazon.com/net/post/Tx2R0WG46GQI1JI/DynamoDB-Series-Document-Model) 
+  [DynamoDB 系列 - 转换架构](http://blogs.aws.amazon.com/net/post/Tx2TCOGWG7ARUH5/DynamoDB-Series-Conversion-Schemas) 
+  [DynamoDB 系列 - 对象持久化模型](http://blogs.aws.amazon.com/net/post/Tx20L86FLMBW51P/DynamoDB-Series-Object-Persistence-Model) 
+  [DynamoDB 系列 - 表达式](http://blogs.aws.amazon.com/net/post/TxZQM7VA9AUZ9L/DynamoDB-Series-Expressions) 
+  [在 Amazon DynamoDB 上使用表达式和 适用于 .NET 的 AWS SDK](dynamodb-expressions.md) 
+  [Amazon DynamoDB 中的 JSON 支持](dynamodb-json.md) 

 **低级模型、信息和示例** 
+  [使用 适用于 .NET 的 AWS SDK 低级 API 处理表](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetWorkingWithTables.html) 
+  [使用 适用于 .NET 的 AWS SDK 低级 API 处理项目](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetItemCRUD.html) 
+  [使用 适用于 .NET 的 AWS SDK 低级 API 查询表](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetQuerying.html) 
+  [使用 适用于 .NET 的 AWS SDK 低级 API 扫描表格](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetScanning.html) 
+  [使用 适用于 .NET 的 AWS SDK 低级 API 处理本地二级索引](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LSILowLevelDotNet.html) 
+  [使用 适用于 .NET 的 AWS SDK 低级 API 使用全局二级索引](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSILowLevelDotNet.html) 

 **文档模型、信息和示例** 
+  [DynamoDB 数据类型](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModel.DataTypes) 
+  [迪纳摩 DBEntry](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TDynamoDBv2DocumentModelDynamoDBEntry.html) 
+  [.NET：文档模型](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DotNetSDKMidLevel.html) 

 **对象持久性模型、信息和示例** 
+  [.NET：对象持久化模型](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DotNetSDKHighLevel.html) 

 **其他有用信息** 
+ 有关通过 .NET Aspire 使用 Amazon DynamoDB local 进行开发的信息，请参阅[将 AWS 与 .NET Aspire 集成](aspire-integrations.md)。

**Topics**
+ [

## 低级模型
](#dynamodb-intro-apis-low-level)
+ [

## 文档模型
](#dynamodb-intro-apis-document)
+ [

## 对象持久化模型
](#dynamodb-intro-apis-object-persistence)
+ [

## 更多信息
](#dynamodb-intro-more-info)
+ [使用表达式](dynamodb-expressions.md)
+ [JSON 支持](dynamodb-json.md)

# 在 Amazon DynamoDB 上使用表达式和 适用于 .NET 的 AWS SDK
<a name="dynamodb-expressions"></a>

**注意**  
本主题中的信息特定于基于.NET Framework 和 3.3 及更早 适用于 .NET 的 AWS SDK 版本的项目。

以下代码示例演示如何使用通过表达式对 DynamoDB 适用于 .NET 的 AWS SDK 进行编程。*表达式*表示您希望从 DynamoDB 表中的某个项目读取到的属性。您还可以在编写项目时使用表达式指示任意必需满足的条件（也称为*有条件更新*），以及需要如何更新属性。一些更新示例使用新值替换属性，或者将新数据添加到列表或映射。有关更多信息，请参阅[使用表达式读取和写入项目](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.html)。

**Topics**
+ [

## 示例数据
](#dynamodb-expressions-sample-data)
+ [

## 使用表达式和项目的主键获取单个项目
](#dynamodb-expressions-get-item)
+ [

## 使用表达式和表主键获取多个项目
](#dynamodb-expressions-query)
+ [

## 使用表达式和其他项目属性获取多个项目
](#dynamodb-expressions-scan)
+ [

## 输出项目
](#dynamodb-expressions-print-item)
+ [

## 使用表达式创建或替换项目
](#dynamodb-expressions-put-item)
+ [

## 使用表达式更新项目
](#dynamodb-expressions-update-item)
+ [

## 使用表达式删除项目
](#dynamodb-expressions-delete-item)
+ [

## 更多信息
](#dynamodb-expressions-resources)

## 示例数据
<a name="dynamodb-expressions-sample-data"></a>

此主题中的代码示例依赖于名为 `ProductCatalog` 的 DynamoDB 表中的以下两个示例项目。这些项目描述一家虚构自行车商店目录中产品条目的相关信息。这些项目基于[案例研究：A Ite ProductCatalog m](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.CaseStudy.html) 中提供的示例。`BOOL`、`L`、`M`、`N`、`NS`、`S` 和 `SS` 等数据类型描述符对应于 [JSON 数据格式](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataFormat.html)中的那些描述符。

```
{
  "Id": {
    "N": "205"
  },
  "Title": {
    "S": "20-Bicycle 205"
  },
  "Description": {
    "S": "205 description"
  },
  "BicycleType": {
    "S": "Hybrid"
  },
  "Brand": {
    "S": "Brand-Company C"
  },
  "Price": {
    "N": "500"
  },
  "Gender": {
    "S": "B"
  },
  "Color": {
    "SS": [
      "Red",
      "Black"
    ]
  },
  "ProductCategory": {
    "S": "Bike"
  },
  "InStock": {
    "BOOL": true
  },
  "QuantityOnHand": {
    "N": "1"
  },
  "RelatedItems": {
    "NS": [
      "341",
      "472",
      "649"
    ]
  },
  "Pictures": {
    "L": [
      {
        "M": {
          "FrontView": {
            "S": "http://example/products/205_front.jpg"
          }
        }
      },
      {
        "M": {
          "RearView": {
            "S": "http://example/products/205_rear.jpg"
          }
        }
      },
      {
        "M": {
          "SideView": {
            "S": "http://example/products/205_left_side.jpg"
          }
        }
      }
    ]
  },
  "ProductReviews": {
    "M": {
      "FiveStar": {
        "SS": [
          "Excellent! Can't recommend it highly enough! Buy it!",
          "Do yourself a favor and buy this."
        ]
      },
      "OneStar": {
        "SS": [
          "Terrible product! Do not buy this."
        ]
      }
    }
  }
},
{
  "Id": {
    "N": "301"
  },
  "Title": {
    "S": "18-Bicycle 301"
  },
  "Description": {
    "S": "301 description"
  },
  "BicycleType": {
    "S": "Road"
  },
  "Brand": {
    "S": "Brand-Company C"
  },
  "Price": {
    "N": "185"
  },
  "Gender": {
    "S": "F"
  },
  "Color": {
    "SS": [
      "Blue",
      "Silver"
    ]
  },
  "ProductCategory": {
    "S": "Bike"
  },
  "InStock": {
    "BOOL": true
  },
  "QuantityOnHand": {
    "N": "3"
  },
  "RelatedItems": {
    "NS": [
      "801",
      "822",
      "979"
    ]
  },
  "Pictures": {
    "L": [
      {
        "M": {
          "FrontView": {
            "S": "http://example/products/301_front.jpg"
          }
        }
      },
      {
        "M": {
          "RearView": {
            "S": "http://example/products/301_rear.jpg"
          }
        }
      },
      {
        "M": {
          "SideView": {
            "S": "http://example/products/301_left_side.jpg"
          }
        }
      }
    ]
  },
  "ProductReviews": {
    "M": {
      "FiveStar": {
        "SS": [
          "My daughter really enjoyed this bike!"
        ]
      },
      "ThreeStar": {
        "SS": [
          "This bike was okay, but I would have preferred it in my color.",
	      "Fun to ride."
        ]
      }
    }
  }
}
```

## 使用表达式和项目的主键获取单个项目
<a name="dynamodb-expressions-get-item"></a>

以下示例介绍了 `Amazon.DynamoDBv2.AmazonDynamoDBClient.GetItem` 方法和一组表达式，用于获取并输出 `Id` 为 `205` 的项目。只返回项目的以下属性：`Id`、`Title`、`Description`、`Color`、`RelatedItems`、`Pictures` 和 `ProductReviews`。

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();
var request = new GetItemRequest
{
  TableName = "ProductCatalog",
  ProjectionExpression = "Id, Title, Description, Color, #ri, Pictures, #pr",
  ExpressionAttributeNames = new Dictionary<string, string>
  {
    { "#pr", "ProductReviews" },
    { "#ri", "RelatedItems" }
  },
  Key = new Dictionary<string, AttributeValue>
  {
    { "Id", new AttributeValue { N = "205" } }
  },
};
var response = client.GetItem(request);

// PrintItem() is a custom function.
PrintItem(response.Item);
```

在上述示例中，`ProjectionExpression` 属性指定要返回的属性。`ExpressionAttributeNames` 属性指定占位符 `#pr` (表示 `ProductReviews` 属性) 和占位符 `#ri` (表示 `RelatedItems` 属性)。对 `PrintItem` 的调用引用自定义函数，如[输出项目](#dynamodb-expressions-print-item)中所述。

## 使用表达式和表主键获取多个项目
<a name="dynamodb-expressions-query"></a>

以下示例介绍了 `Amazon.DynamoDBv2.AmazonDynamoDBClient.Query` 方法和一组表达式，仅在 `Id` 的值大于 `301` 时，获取并输出 `Price` 为 `150` 的项目。只返回项目的以下属性：`Id`、`Title` 以及所有 `ThreeStar` 中的所有 `ProductReviews` 属性。

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();
var request = new QueryRequest
{
  TableName = "ProductCatalog",
  KeyConditions = new Dictionary<string,Condition>
  {
    { "Id", new Condition()
      {
        ComparisonOperator = ComparisonOperator.EQ,
        AttributeValueList = new List<AttributeValue>
        {
          new AttributeValue { N = "301" }
        }
      }
    }
  },
  ProjectionExpression = "Id, Title, #pr.ThreeStar",
  ExpressionAttributeNames = new Dictionary<string, string>
  {
    { "#pr", "ProductReviews" },
    { "#p", "Price" }
  },
  ExpressionAttributeValues = new Dictionary<string,AttributeValue>
  {
    { ":val", new AttributeValue { N = "150" } }
  },
  FilterExpression = "#p > :val"
};
var response = client.Query(request);

foreach (var item in response.Items)
{
  // Write out the first page of an item's attribute keys and values.
  // PrintItem() is a custom function.
  PrintItem(item);
  Console.WriteLine("=====");
}
```

在上述示例中，`ProjectionExpression` 属性指定要返回的属性。`ExpressionAttributeNames` 属性指定占位符 `#pr`（表示 `ProductReviews` 属性）和占位符 `#p`（表示 `Price` 属性）。`#pr.ThreeStar` 指定只返回 `ThreeStar` 属性。`ExpressionAttributeValues` 属性指定占位符 `:val` 来表示值 `150`。`FilterExpression` 属性指定 `#p` (`Price`) 必须大于 `:val` (`150`)。对 `PrintItem` 的调用引用自定义函数，如[输出项目](#dynamodb-expressions-print-item)中所述。

## 使用表达式和其他项目属性获取多个项目
<a name="dynamodb-expressions-scan"></a>

以下示例介绍了 `Amazon.DynamoDBv2.AmazonDynamoDBClient.Scan` 方法和一组表达式，用于获取并输出 `ProductCategory` 为 `Bike` 的所有项目。只返回项目的以下属性：`Id`、`Title` 以及 `ProductReviews` 中的所有属性。

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();
var request = new ScanRequest
{
  TableName = "ProductCatalog",
  ProjectionExpression = "Id, Title, #pr",
  ExpressionAttributeValues = new Dictionary<string,AttributeValue>
  {
    { ":catg", new AttributeValue { S = "Bike" } }
  },
  ExpressionAttributeNames = new Dictionary<string, string>
  {
    { "#pr", "ProductReviews" },
    { "#pc", "ProductCategory" }
  },
  FilterExpression = "#pc = :catg",  
};
var response = client.Scan(request);

foreach (var item in response.Items)
{
  // Write out the first page/scan of an item's attribute keys and values.
  // PrintItem() is a custom function.
  PrintItem(item);
  Console.WriteLine("=====");
}
```

在上述示例中，`ProjectionExpression` 属性指定要返回的属性。`ExpressionAttributeNames` 属性指定占位符 `#pr` (表示 `ProductReviews` 属性) 和占位符 `#pc` (表示 `ProductCategory` 属性)。`ExpressionAttributeValues` 属性指定占位符 `:catg` 来表示值 `Bike`。`FilterExpression` 属性指定 `#pc` (`ProductCategory`) 必须等于 `:catg` (`Bike`)。对 `PrintItem` 的调用引用自定义函数，如[输出项目](#dynamodb-expressions-print-item)中所述。

## 输出项目
<a name="dynamodb-expressions-print-item"></a>

以下示例演示如何输出项目的属性和值。此示例已在前面的几个示例中使用过，这些示例演示如何[使用表达式和项目的主键获取单个项目](#dynamodb-expressions-get-item)、[使用表达式和表主键获取多个项目](#dynamodb-expressions-query)以及[使用表达式和其他项目属性获取多个项目](#dynamodb-expressions-scan)。

```
// using Amazon.DynamoDBv2.Model;

// Writes out an item's attribute keys and values.
public static void PrintItem(Dictionary<string, AttributeValue> attrs)
{
  foreach (KeyValuePair<string, AttributeValue> kvp in attrs)
  {
    Console.Write(kvp.Key + " = ");
    PrintValue(kvp.Value);
  }
}

// Writes out just an attribute's value.
public static void PrintValue(AttributeValue value)
{
  // Binary attribute value.
  if (value.B != null)
  {
    Console.Write("Binary data");
  }
  // Binary set attribute value.
  else if (value.BS.Count > 0)
  {
    foreach (var bValue in value.BS)
    {
      Console.Write("\n  Binary data");
    }
  }
  // List attribute value.
  else if (value.L.Count > 0)
  {
    foreach (AttributeValue attr in value.L)
    {
      PrintValue(attr);
    }
  }
  // Map attribute value.
  else if (value.M.Count > 0)
  {
    Console.Write("\n");
    PrintItem(value.M);
  }
  // Number attribute value.
  else if (value.N != null)
  {
    Console.Write(value.N);
  }
  // Number set attribute value.
  else if (value.NS.Count > 0)
  {
    Console.Write("{0}", string.Join("\n", value.NS.ToArray()));
  }
  // Null attribute value.
  else if (value.NULL)
  {
    Console.Write("Null");
  }
  // String attribute value.
  else if (value.S != null)
  {
    Console.Write(value.S);
  }
  // String set attribute value.
  else if (value.SS.Count > 0)
  {
    Console.Write("{0}", string.Join("\n", value.SS.ToArray()));
  }
  // Otherwise, boolean value.
  else
  {
    Console.Write(value.BOOL);
  }
 
  Console.Write("\n");
}
```

在前面的示例中，每个属性值都有多个 data-type-specific属性，可以通过评估这些属性来确定打印属性的正确格式。这些属性包括 `B`、`BOOL`、`BS`、`L`、`M`、`N`、`NS`、`NULL`、`S` 和 `SS`，对应于 [JSON 数据格式](DataFormat.html)中的那些属性。对于 `B`、`N`、`NULL` 和 `S` 等属性，如果对应属性不是 `null`，则属性是对应的非 `null` 数据类型。对于诸如`BS`、、`L`、`M``NS``SS`、和之类的属性，如果`Count`大于零，则该属性属于相应 non-zero-value的数据类型。如果该属性的所有属性均为`null`或`Count`等于零，则该属性对应于`BOOL`数据类型。 data-type-specific

## 使用表达式创建或替换项目
<a name="dynamodb-expressions-put-item"></a>

以下示例介绍了 `Amazon.DynamoDBv2.AmazonDynamoDBClient.PutItem` 方法和一组表达式，用于更新 `Title` 为 `18-Bicycle 301` 的项目。如果项目不存在，将添加新项目。

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();
var request = new PutItemRequest
{
  TableName = "ProductCatalog",
  ExpressionAttributeNames = new Dictionary<string, string>
  {
    { "#title", "Title" }
  },
  ExpressionAttributeValues = new Dictionary<string, AttributeValue>
  {
    { ":product", new AttributeValue { S = "18-Bicycle 301" } }
  },
  ConditionExpression = "#title = :product", 
  // CreateItemData() is a custom function.
  Item = CreateItemData()
};
client.PutItem(request);
```

在上述示例中，`ExpressionAttributeNames` 属性指定占位符 `#title`，以表示 `Title` 属性。`ExpressionAttributeValues` 属性指定占位符 `:product` 来表示值 `18-Bicycle 301`。`ConditionExpression` 属性指定 `#title` (`Title`) 必须等于 `:product` (`18-Bicycle 301`)。对 `CreateItemData` 的调用引用以下自定义函数：

```
// using Amazon.DynamoDBv2.Model;

// Provides a sample item that can be added to a table.
public static Dictionary<string, AttributeValue> CreateItemData()
{
  var itemData = new Dictionary<string, AttributeValue>
  {
    { "Id", new AttributeValue { N = "301" } },
    { "Title", new AttributeValue { S = "18\" Girl's Bike" } },
    { "BicycleType", new AttributeValue { S = "Road" } },
    { "Brand" , new AttributeValue { S = "Brand-Company C" } },
    { "Color", new AttributeValue { SS = new List<string>{ "Blue", "Silver" } } },
    { "Description", new AttributeValue { S = "301 description" } },
    { "Gender", new AttributeValue { S = "F" } },
    { "InStock", new AttributeValue { BOOL = true } },
    { "Pictures", new AttributeValue { L = new List<AttributeValue>{ 
      { new AttributeValue { M = new Dictionary<string,AttributeValue>{
        { "FrontView", new AttributeValue { S = "http://example/products/301_front.jpg" } } } } },
      { new AttributeValue { M = new Dictionary<string,AttributeValue>{
        { "RearView", new AttributeValue {S = "http://example/products/301_rear.jpg" } } } } },
      { new AttributeValue { M = new Dictionary<string,AttributeValue>{
        { "SideView", new AttributeValue { S = "http://example/products/301_left_side.jpg" } } } } }
    } } },
    { "Price", new AttributeValue { N = "185" } },
    { "ProductCategory", new AttributeValue { S = "Bike" } },
    { "ProductReviews", new AttributeValue { M = new Dictionary<string,AttributeValue>{
      { "FiveStar", new AttributeValue { SS = new List<string>{
        "My daughter really enjoyed this bike!" } } },
      { "OneStar", new AttributeValue { SS = new List<string>{
        "Fun to ride.",
        "This bike was okay, but I would have preferred it in my color." } } }
    } } },
    { "QuantityOnHand", new AttributeValue { N = "3" } },
    { "RelatedItems", new AttributeValue { NS = new List<string>{ "979", "822", "801" } } }
  };

  return itemData;
}
```

在上述示例中，具有示例数据的示例项目返回到调用方。构建了一系列属性和对应值，使用 `BOOL`、`L`、`M`、`N`、`NS`、`S` 和 `SS` 等数据类型，它们对应于 [JSON 数据格式](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataFormat.html)中的那些类型。

## 使用表达式更新项目
<a name="dynamodb-expressions-update-item"></a>

以下示例介绍了 `Amazon.DynamoDBv2.AmazonDynamoDBClient.UpdateItem` 方法和一组表达式，用于将 `Title` 为 `18" Girl's Bike` 的项目的 `Id` 更改为 `301`。

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();
var request = new UpdateItemRequest
{
  TableName = "ProductCatalog",
  Key = new Dictionary<string,AttributeValue>
  {
     { "Id", new AttributeValue { N = "301" } }
  },
  ExpressionAttributeNames = new Dictionary<string, string>
  {
    { "#title", "Title" }
  },
  ExpressionAttributeValues = new Dictionary<string, AttributeValue>
  {
    { ":newproduct", new AttributeValue { S = "18\" Girl's Bike" } }
  },
  UpdateExpression = "SET #title = :newproduct"
};
client.UpdateItem(request);
```

在上述示例中，`ExpressionAttributeNames` 属性指定占位符 `#title`，以表示 `Title` 属性。`ExpressionAttributeValues` 属性指定占位符 `:newproduct` 来表示值 `18" Girl's Bike`。`UpdateExpression` 属性指定将 `#title` (`Title`) 更改为 `:newproduct` (`18" Girl's Bike`)。

## 使用表达式删除项目
<a name="dynamodb-expressions-delete-item"></a>

以下示例介绍了 `Amazon.DynamoDBv2.AmazonDynamoDBClient.DeleteItem` 方法和一组表达式，仅在项目的 `Title` 为 `18-Bicycle 301` 时，删除 `Id` 为 `301` 的项目。

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();
var request = new DeleteItemRequest
{
  TableName = "ProductCatalog",
  Key = new Dictionary<string,AttributeValue>
  {
     { "Id", new AttributeValue { N = "301" } }
  },
  ExpressionAttributeNames = new Dictionary<string, string>
  {
    { "#title", "Title" }
  },
  ExpressionAttributeValues = new Dictionary<string, AttributeValue>
  {
    { ":product", new AttributeValue { S = "18-Bicycle 301" } }
  },
  ConditionExpression = "#title = :product"
};
client.DeleteItem(request);
```

在上述示例中，`ExpressionAttributeNames` 属性指定占位符 `#title`，以表示 `Title` 属性。`ExpressionAttributeValues` 属性指定占位符 `:product` 来表示值 `18-Bicycle 301`。`ConditionExpression` 属性指定 `#title` (`Title`) 必须等于 `:product` (`18-Bicycle 301`)。

## 更多信息
<a name="dynamodb-expressions-resources"></a>

有关更多信息以及代码示例，请参阅：
+  [DynamoDB 系列 - 表达式](http://blogs.aws.amazon.com/net/post/TxZQM7VA9AUZ9L/DynamoDB-Series-Expressions) 
+  [使用投影表达式访问项目属性](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html) 
+  [为属性名称和值使用占位符](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ExpressionPlaceholders.html) 
+  [使用条件表达式指定条件](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html) 
+  [使用更新表达式修改项目和属性](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.Modifying.html) 
+  [使用 适用于 .NET 的 AWS SDK 低级 API 处理项目](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetItemCRUD.html) 
+  [使用 适用于 .NET 的 AWS SDK 低级 API 查询表](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetQuerying.html) 
+  [使用 适用于 .NET 的 AWS SDK 低级 API 扫描表格](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetScanning.html) 
+  [使用 适用于 .NET 的 AWS SDK 低级 API 处理本地二级索引](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LSILowLevelDotNet.html) 
+  [使用 适用于 .NET 的 AWS SDK 低级 API 使用全局二级索引](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSILowLevelDotNet.html) 

# Amazon DynamoDB 中的 JSON 支持
<a name="dynamodb-json"></a>

**注意**  
本主题中的信息特定于基于.NET Framework 和 3.3 及更早 适用于 .NET 的 AWS SDK 版本的项目。

使用亚马逊 DynamoDB 时 适用于 .NET 的 AWS SDK 支持 JSON 数据。这使您能够更轻松地从 DynamoDB 中获取 JSON 格式的数据以及将 JSON 文档插入到其中。

**Topics**
+ [

## 从 DynamoDB 表以 JSON 格式获取数据
](#dynamodb-json-get-table-data)
+ [

## 将 JSON 格式数据插入 DynamoDB 表
](#dynamodb-json-insert-table-data)
+ [

## DynamoDB 数据类型转换为 JSON
](#dynamodb-json-datatypes)
+ [

## 更多信息
](#dynamodb-json-more-info)

## 从 DynamoDB 表以 JSON 格式获取数据
<a name="dynamodb-json-get-table-data"></a>

以下示例显示了如何以 JSON 格式从 DynamoDB 表中获取数据：

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.DocumentModel;

var client = new AmazonDynamoDBClient();
var table = Table.LoadTable(client, "AnimalsInventory");
var item = table.GetItem(3, "Horse");

var jsonText = item.ToJson();
Console.Write(jsonText);
      
// Output:
//   {"Name":"Shadow","Type":"Horse","Id":3}

var jsonPrettyText = item.ToJsonPretty();
Console.WriteLine(jsonPrettyText);
      
// Output:
//   {
//     "Name" : "Shadow",
//     "Type" : "Horse",
//     "Id"   : 3
//   }
```

在上述示例中，`Document` 类的 `ToJson` 方法将表中的项目转换为 JSON 格式的字符串。项目通过 `Table` 类的 `GetItem` 方法检索。为了确定要获取的项目，在本示例中，该`GetItem`方法使用目标项目 hash-and-range的主键。为确定要从中获取项目的表，`Table` 类的 `LoadTable` 方法使用 `AmazonDynamoDBClient` 类的实例以及 DynamoDB 中的目标表名。

## 将 JSON 格式数据插入 DynamoDB 表
<a name="dynamodb-json-insert-table-data"></a>

以下示例演示如何使用 JSON 格式将项目插入到 DynamoDB 表：

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.DocumentModel;

var client = new AmazonDynamoDBClient();
var table = Table.LoadTable(client, "AnimalsInventory");
var jsonText = "{\"Id\":6,\"Type\":\"Bird\",\"Name\":\"Tweety\"}";
var item = Document.FromJson(jsonText);

table.PutItem(item);
```

在上述示例中，`FromJson` 类的 `Document` 方法将 JSON 格式的字符串转换为项目。项目通过 `PutItem` 类的 `Table` 方法插入表中，该方法使用包含项目的 `Document` 类的实例。为确定要插入项目的表，调用 `Table` 类的 `LoadTable` 方法，并指定 `AmazonDynamoDBClient` 类的实例以及 DynamoDB 中的目标表名。

## DynamoDB 数据类型转换为 JSON
<a name="dynamodb-json-datatypes"></a>

当您调用 `Document` 类的 `ToJson` 方法，然后在生成的 JSON 数据上调用 `FromJson` 方法以将 JSON 数据转换回 `Document` 类的实例时，一些 DynamoDB 数据类型不会按预期转换。具体来说：
+ DynamoDB 集（`SS`、`NS` 和 `BS` 类型）将转换为 JSON 数组。
+ DynamoDB 二进制标量和集（`B` 和 `BS` 类型）将转换为 base64 编码的 JSON 字符串或字符串列表。

  在此情况下，您必须调用 `DecodeBase64Attributes` 类的 `Document` 方法，使用正确的二进制表示形式替换 base64 编码的 JSON 数据。以下示例使用正确的二进制表示形式，在 `Document` 类的实例中，替换 base64 编码的名为 `Picture` 的二进制标量项目属性。此示例还在 `Document` 类的相同实例中，为名为 `RelatedPictures` 的 base64 编码二进制集项目属性执行相同的操作。

  ```
  item.DecodeBase64Attributes("Picture", "RelatedPictures");
  ```

## 更多信息
<a name="dynamodb-json-more-info"></a>

有关使用 DynamoDB 编程 JSON 的更多信息和示例， 适用于 .NET 的 AWS SDK请参阅：
+  [DynamoDB JSON 支持](https://aws.amazon.com/blogs/developer/dynamodb-json-support/) 
+  [Amazon DynamoDB 更新 - JSON、更广泛的免费套餐、灵活扩展、更大的项目](https://aws.amazon.com/blogs/aws/dynamodb-update-json-and-more/) 