Exemplo: operações CRUD usando o modelo de persistência de objetos do AWS SDK for .NET - Amazon DynamoDB

Exemplo: operações CRUD usando o modelo de persistência de objetos do AWS SDK for .NET

O exemplo de código C# a seguir declara uma classe Book com as propriedades Id, Title, Isbn e BookAuthors. O exemplo usa os atributos de persistência de objetos para mapear essas propriedades na tabela ProductCatalogno Amazon DynamoDB. Depois, o exemplo usa a classe DynamoDBContext para ilustrar as operações típicas de criação, leitura, atualização e exclusão (CRUD). O exemplo cria uma Book instance de exemplo e a salva na tabela ProductCatalog. Em seguida, ele recupera o item do livro e atualiza suas propriedades Isbn e BookAuthors. Observe que a atualização substitui a lista de autores existentes. Finalmente, o exemplo exclui o item de livro.

Para obter mais informações sobre a tabelas ProductCatalog usada neste exemplo, consulte Criar tabelas e carregar dados para exemplos de código no DynamoDB. Para ver as instruções passo a passo para testar o exemplo a seguir, consulte Exemplos de código .NET.

nota

O exemplo a seguir não funciona com o .NET Core porque ele não oferece suporte a métodos síncronos. Para obter mais informações, consulte APIs assíncronas da AWS para o .NET.

exemplo Operações CRUD usando a classe DynamoDBContext
/// <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"); } } }
exemplo
Informações sobre a classe Book a serem adicionadas à tabela 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; } }