本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
步骤 2:使用低级 API 创建 DynamoDB 表
中的文档模型未提供用于创建表,因此您必须使用低级别 适用于 .NET 的 AWS 开发工具包。APIs 有关更多信息,请参阅在 .NET 中处理 DynamoDB 表。
在 Microsoft .NET 和 DynamoDB 教程的本步骤中,您将在 Movies
中创建一个名为 Amazon DynamoDB 的表。表的主键由以下属性组成:
-
year
– 分区键。对于数字,AttributeType
为N
。注意 由于“year”是 DynamoDB 中的保留字,因此在低级别表达式中引用
#yr
对象时,您需要使用ExpressionAttributeNames
对象为其创建别名(例如 )。 -
title
– 排序键。对于字符串,AttributeType
为S
。
中的 Main
函数通过等待 DynamoDB_intro
文件中实现的异步 CreatingTable_async
函数来执行此操作。02_CreatingTable.cs
using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.DynamoDBv2.Model; namespace DynamoDB_intro { public static partial class DdbIntro { public static async Task<bool> CheckingTableExistence_async(string tblNm) { var response = await DdbIntro.Client.ListTablesAsync(); return response.TableNames.Contains(tblNm); } public static async Task<bool> CreateTable_async(string tableName, List<AttributeDefinition> tableAttributes, List<KeySchemaElement> tableKeySchema, ProvisionedThroughput provisionedThroughput) { bool response = true; // Build the 'CreateTableRequest' structure for the new table var request = new CreateTableRequest { TableName = tableName, AttributeDefinitions = tableAttributes, KeySchema = tableKeySchema, // Provisioned-throughput settings are always required, // although the local test version of DynamoDB ignores them. ProvisionedThroughput = provisionedThroughput }; try { var makeTbl = await DdbIntro.Client.CreateTableAsync(request); } catch (Exception) { response = false; } return response; } public static async Task<TableDescription> GetTableDescription(string tableName) { TableDescription result = null; // If the table exists, get its description. try { var response = await DdbIntro.Client.DescribeTableAsync(tableName); result = response.Table; } catch (Exception) {} return result; } } }
函数首先等待一个异步 CreatingTable_async
函数来确定名为“Movies”的表是否已存在。checkingTableExistence_async
如果表存在,checkingTableExistence_async
将检索现有 TableDescription
的 Table
。
如果该表尚不存在,CreatingTable_async
将等待 CreateNewTable_async
使用 Movies
客户端 API DynamoDB 创建 CreateTableAsync
表。
示例尽可能使用异步方法,而不是同步方法。DynamoDB_intro
这是因为 .NET Core 仅支持异步方法,在性能至关重要时,异步模型通常更可取。有关更多信息,请参阅适用于 .NET 的 AWS 异步 APIs。
要了解有关管理表的更多信息,请参阅使用 DynamoDB 中的表和数据。