範例CRUD:使用 AWS SDK for .NET 對象持久性模型 - Amazon DynamoDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

範例CRUD:使用 AWS SDK for .NET 對象持久性模型

下列 C# 程式碼範例會宣告具有 IdTitleIsbnBookAuthors 屬性的 Book 類別。範例會使用物件持久性屬性,將這些屬性映射至 Amazon DynamoDB 中的 ProductCatalog 資料表。然後,範例會使用 D ynamoDBContext 類別來說明典型的建立、讀取、更新和 delete (CRUD) 作業。此範例會建立範例Book instance並將其儲存至ProductCatalog表格中。它會接著擷取書籍項目並更新其 IsbnBookAuthors 屬性。請注意,更新會取代現有的作者清單。最後,該範例會刪除書籍項目。

如需此範例中所使用 ProductCatalog 資料表的詳細資訊,請參閱 在 DynamoDB 中建立資料表,以及載入程式碼範例的資料。如需測試下列範例的 step-by-step 指示,請參閱。 NET程式碼範例

注意

下列範例無法使用。 NET核心,因為它不支持同步方法。如需詳細資訊,請參閱 AWS 非同步APIs的. NET

範例 CRUD使用 D ynamoDBContext 類的操作
/// <summary> /// Shows how to perform high-level CRUD operations on an Amazon DynamoDB /// table. /// </summary> public class HighLevelItemCrud { public static async Task Main() { var client = new AmazonDynamoDBClient(); DynamoDBContext context = new DynamoDBContext(client); await PerformCRUDOperations(context); } public static async Task PerformCRUDOperations(IDynamoDBContext 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 to the ProductCatalog table. await context.SaveAsync(myBook); // Retrieve the book from the ProductCatalog table. Book bookRetrieved = await context.LoadAsync<Book>(bookId); // Update some properties. bookRetrieved.Isbn = "222-2222221001"; // Update existing authors list with the following values. bookRetrieved.BookAuthors = new List<string> { " Author 1", "Author x" }; await context.SaveAsync(bookRetrieved); // Retrieve the updated book. This time, add the optional // ConsistentRead parameter using DynamoDBContextConfig object. await context.LoadAsync<Book>(bookId, new DynamoDBContextConfig { ConsistentRead = true, }); // Delete the book. await context.DeleteAsync<Book>(bookId); // Try to retrieve deleted book. It should return null. Book deletedBook = await context.LoadAsync<Book>(bookId, new DynamoDBContextConfig { ConsistentRead = true, }); if (deletedBook == null) { Console.WriteLine("Book is deleted"); } } }
範例
要新增至表 ProductCatalog 格的圖書課程資訊
/// <summary> /// A class representing book information to be added to the Amazon DynamoDB /// ProductCatalog table. /// </summary> [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; } }