示例:使用 Amazon SDK for .NET 对象持久化模型的 CRUD 操作 - Amazon DynamoDB
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

示例:使用 Amazon SDK for .NET 对象持久化模型的 CRUD 操作

下面的 C# 代码示例声明具有 IdTitleISBNAuthors 属性的 Book 类。该示例使用对象持久化属性将这些属性映射到 Amazon DynamoDB 的 ProductCatalog 表。该示例然后使用 DynamoDBContext 来说明典型创建、读取、更新和删除 (CRUD) 操作。该示例创建一个示例 Book 实例并将其保存到 ProductCatalog 表。然后,它检索书籍项目并更新其 ISBNAuthors 属性。请注意,此更新将替换现有的作者列表。最后,该示例删除了书籍项目。

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

注意

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

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