Ejemplo: operaciones CRUD con el modelo de persistencia de objetos de AWS SDK for .NET - Amazon DynamoDB

Ejemplo: operaciones CRUD con el modelo de persistencia de objetos de AWS SDK for .NET

En el siguiente ejemplo de código C# se define una clase Book con las propiedades Id, Title, Isbn y BookAuthors. Se utilizan los atributos de persistencia de objetos para mapear estas propiedades a la tabla ProductCatalog de Amazon DynamoDB. A continuación, en el ejemplo se usa la clase DynamoDBContext para ilustrar las operaciones típicas de creación, lectura, actualización y eliminación (CRUD). En el ejemplo se crea una Book instance de ejemplo y se guarda en la tabla ProductCatalog. A continuación, recupera el elemento del libro y actualiza sus propiedades Isbn y BookAuthors. Tenga en cuenta que la actualización sustituye la lista de autores existente. Por último, en el ejemplo se elimina el elemento de libro.

Para obtener más información sobre la tabla ProductCatalog que se utilizan en este ejemplo, consulte Creación de tablas y carga de datos para ejemplos de código en DynamoDB. Para obtener instrucciones paso a paso sobre cómo realizar las pruebas del ejemplo siguiente, consulte Ejemplos de código .NET.

nota

Los ejemplos que aparecen en esta sección no funcionan con .NET Core, ya que no es compatible con los métodos síncronos. Para obtener más información, consulte API asincrónicas de AWS para .NET.

ejemplo Operaciones CRUD con la clase 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"); } } }
ejemplo
Información de la clase Book para agregar a la tabla 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; } }