Amazon DynamoDB
开发人员指南 (API Version 2012-08-10)
AWS 服务或AWS文档中描述的功能,可能因地区/位置而异。点 击 Getting Started with Amazon AWS to see specific differences applicable to the China (Beijing) Region.

示例:使用适用于 .NET 的 AWS 开发工具包对象持久化模型执行 CRUD 操作

以下 C# 代码示例声明一个具有 Id、title、ISBN 和 Authors 属性的 Book 类。它使用对象持久化属性将这些属性映射到 DynamoDB 中的 ProductCatalog 表。然后,代码示例使用 DynamoDBContext 说明典型的 CRUD 操作。该示例创建一个示例 Book 实例,并将其保存到 ProductCatalog 表。然后该示例检索图书项目,并更新其 ISBN 和 Authors 属性。请注意,这一更新会替换现有的作者列表。该示例最终删除该图书项目。

有关此示例中使用的 ProductCatalog 表的更多信息,请参阅创建表并加载示例数据。有关测试以下示例的分步说明,请参阅.NET 代码示例

注意

以下示例不适用于 .NET Core,因为它不支持同步方法。有关更多信息,请参阅适用于 .NET 的 AWS 异步 API

Copy
using System; using System.Collections.Generic; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.DataModel; using Amazon.Runtime; namespace com.amazonaws.codesamples { class HighLevelItemCRUD { private static AmazonDynamoDBClient client = new AmazonDynamoDBClient(); static void Main(string[] args) { try { DynamoDBContext context = new DynamoDBContext(client); TestCRUDOperations(context); Console.WriteLine("To continue, press Enter"); Console.ReadLine(); } catch (AmazonDynamoDBException e) { Console.WriteLine(e.Message); } catch (AmazonServiceException e) { Console.WriteLine(e.Message); } catch (Exception e) { Console.WriteLine(e.Message); } } private static void TestCRUDOperations(DynamoDBContext context) { int bookID = 1001; // Some unique value. Book myBook = new Book { Id = bookID, Title = "object persistence-AWS SDK for.NET SDK-Book 1001", ISBN = "111-1111111001", BookAuthors = new List<string> { "Author 1", "Author 2" }, }; // Save the book. context.Save(myBook); // Retrieve the book. Book bookRetrieved = context.Load<Book>(bookID); // Update few properties. bookRetrieved.ISBN = "222-2222221001"; bookRetrieved.BookAuthors = new List<string> { " Author 1", "Author x" }; // Replace existing authors list with this. context.Save(bookRetrieved); // Retrieve the updated book. This time add the optional ConsistentRead parameter using DynamoDBContextConfig object. Book updatedBook = context.Load<Book>(bookID, new DynamoDBContextConfig { ConsistentRead = true }); // Delete the book. context.Delete<Book>(bookID); // Try to retrieve deleted book. It should return null. Book deletedBook = context.Load<Book>(bookID, new DynamoDBContextConfig { ConsistentRead = true }); if (deletedBook == null) Console.WriteLine("Book is deleted"); } } [DynamoDBTable("ProductCatalog")] public class Book { [DynamoDBHashKey] //Partition key public int Id { get; set; } [DynamoDBProperty] public string Title { get; set; } [DynamoDBProperty] public string ISBN { get; set; } [DynamoDBProperty("Authors")] //String Set datatype public List<string> BookAuthors { get; set; } } }