¡Se AWS SDK para .NET ha publicado la versión 4 (V4) del!
Para obtener información sobre los cambios más importantes y la migración de sus aplicaciones, consulte el tema sobre migración.
Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.
Ejemplos SDK para .NET de DynamoDB con (v4)
Los siguientes ejemplos de código muestran cómo realizar acciones e implementar escenarios comunes mediante el uso de AWS SDK para .NET (v4) con DynamoDB.
Los conceptos básicos son ejemplos de código que muestran cómo realizar las operaciones esenciales dentro de un servicio.
Las acciones son extractos de código de programas más grandes y deben ejecutarse en contexto. Mientras las acciones muestran cómo llamar a las distintas funciones de servicio, es posible ver las acciones en contexto en los escenarios relacionados.
En cada ejemplo se incluye un enlace al código de origen completo, con instrucciones de configuración y ejecución del código en el contexto.
Introducción
En los siguientes ejemplos de código, se muestra cómo empezar a utilizar DynamoDB.
- SDK para .NET (v4)
-
nota
Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.Model; using Microsoft.Extensions.DependencyInjection; namespace DynamoDBActions; /// <summary> /// A simple example that demonstrates basic DynamoDB operations. /// </summary> public class HelloDynamoDB { /// <summary> /// HelloDynamoDB lists the existing DynamoDB tables for the default user. /// </summary> /// <param name="args">Command line arguments</param> /// <returns>Async task.</returns> static async Task Main(string[] args) { // Set up dependency injection for Amazon DynamoDB. using var host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args) .ConfigureServices((_, services) => services.AddAWSService<IAmazonDynamoDB>() ) .Build(); // Now the client is available for injection. var dynamoDbClient = host.Services.GetRequiredService<IAmazonDynamoDB>(); try { var request = new ListTablesRequest(); var tableNames = new List<string>(); var paginatorForTables = dynamoDbClient.Paginators.ListTables(request); await foreach (var tableName in paginatorForTables.TableNames) { tableNames.Add(tableName); } Console.WriteLine("Welcome to the DynamoDB Hello Service example. " + "\nLet's list your DynamoDB tables:"); tableNames.ForEach(table => { Console.WriteLine($"Table: {table}"); }); } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB service error occurred while listing tables. {ex.Message}"); } catch (Exception ex) { Console.WriteLine($"An error occurred while listing tables. {ex.Message}"); } } }
-
Para obtener más información sobre la API, consulta ListTablesla Referencia AWS SDK para .NET de la API.
-
Conceptos básicos
En el siguiente ejemplo de código, se muestra cómo:
Creación de una tabla que pueda contener datos de películas.
Colocar, obtener y actualizar una sola película en la tabla.
Escribir los datos de películas en la tabla a partir de un archivo JSON de ejemplo.
Consultar películas que se hayan estrenado en un año determinado.
Buscar películas que se hayan estrenado en un intervalo de años.
Eliminación de una película de la tabla y, a continuación, eliminar la tabla.
- SDK para .NET (v4)
-
nota
Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. /// <summary> /// This example application performs the following basic Amazon DynamoDB /// functions: /// CreateTableAsync /// PutItemAsync /// UpdateItemAsync /// BatchWriteItemAsync /// GetItemAsync /// DeleteItemAsync /// Query /// Scan /// DeleteItemAsync. /// </summary> public class DynamoDbBasics { public static bool IsInteractive = true; // Separator for the console display. private static readonly string SepBar = new string('-', 80); /// <summary> /// The main entry point for the DynamoDB Basics example application. /// </summary> /// <param name="args">Command line arguments.</param> /// <returns>A task representing the asynchronous operation.</returns> public static async Task Main(string[] args) { // Set up dependency injection for Amazon DynamoDB. using var host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args) .ConfigureServices((_, services) => services.AddAWSService<IAmazonDynamoDB>() .AddTransient<DynamoDbWrapper>()) .Build(); // Now the wrapper is available for injection. var dynamoDbWrapper = host.Services.GetRequiredService<DynamoDbWrapper>(); var tableName = "movie_table"; var movieFileName = @"movies.json"; DisplayInstructions(); // Create a new table and wait for it to be active. Console.WriteLine($"Creating the new table: {tableName}"); var success = await dynamoDbWrapper.CreateMovieTableAsync(tableName); Console.WriteLine(success ? $"\nTable: {tableName} successfully created." : $"\nCould not create {tableName}."); WaitForEnter(); // Add a single new movie to the table. var newMovie = new Movie { Year = 2021, Title = "Spider-Man: No Way Home", }; success = await dynamoDbWrapper.PutItemAsync(newMovie, tableName); if (success) { Console.WriteLine($"Added {newMovie.Title} to the table."); } else { Console.WriteLine("Could not add movie to table."); } WaitForEnter(); // Update the new movie by adding a plot and rank. var newInfo = new MovieInfo { Plot = "With Spider-Man's identity now revealed, Peter asks" + "Doctor Strange for help. When a spell goes wrong, dangerous" + "foes from other worlds start to appear, forcing Peter to" + "discover what it truly means to be Spider-Man.", Rank = 9, }; success = await dynamoDbWrapper.UpdateItemAsync(newMovie, newInfo, tableName); if (success) { Console.WriteLine($"Successfully updated the movie: {newMovie.Title}"); } else { Console.WriteLine("Could not update the movie."); } WaitForEnter(); // Add a batch of movies to the DynamoDB table from a list of // movies in a JSON file. var itemCount = await dynamoDbWrapper.BatchWriteItemsAsync(movieFileName, tableName); Console.WriteLine($"Added {itemCount} movies to the table."); WaitForEnter(); // Get a movie by key. (partition + sort) var lookupMovie = new Movie { Title = "Jurassic Park", Year = 1993, }; Console.WriteLine("Looking for the movie \"Jurassic Park\"."); var item = await dynamoDbWrapper.GetItemAsync(lookupMovie, tableName); if (item?.Count > 0) { dynamoDbWrapper.DisplayItem(item); } else { Console.WriteLine($"Couldn't find {lookupMovie.Title}"); } WaitForEnter(); // Delete a movie. var movieToDelete = new Movie { Title = "The Town", Year = 2010, }; success = await dynamoDbWrapper.DeleteItemAsync(tableName, movieToDelete); if (success) { Console.WriteLine($"Successfully deleted {movieToDelete.Title}."); } else { Console.WriteLine($"Could not delete {movieToDelete.Title}."); } WaitForEnter(); // Use Query to find all the movies released in 2010. int findYear = 2010; Console.WriteLine($"Movies released in {findYear}"); var queryCount = await dynamoDbWrapper.QueryMoviesAsync(tableName, findYear); Console.WriteLine($"Found {queryCount} movies released in {findYear}"); WaitForEnter(); // Use Scan to get a list of movies from 2001 to 2011. int startYear = 2001; int endYear = 2011; var scanCount = await dynamoDbWrapper.ScanTableAsync(tableName, startYear, endYear); Console.WriteLine($"Found {scanCount} movies released between {startYear} and {endYear}"); WaitForEnter(); // Delete the table. success = await dynamoDbWrapper.DeleteTableAsync(tableName); if (success) { Console.WriteLine($"Successfully deleted {tableName}"); } else { Console.WriteLine($"Could not delete {tableName}"); } Console.WriteLine("The DynamoDB Basics example application is complete."); WaitForEnter(); } /// <summary> /// Displays the description of the application on the console. /// </summary> private static void DisplayInstructions() { if (!IsInteractive) { return; } Console.Clear(); Console.WriteLine(); Console.Write(new string(' ', 28)); Console.WriteLine("DynamoDB Basics Example"); Console.WriteLine(SepBar); Console.WriteLine("This demo application shows the basics of using DynamoDB with the AWS SDK."); Console.WriteLine(SepBar); Console.WriteLine("The application does the following:"); Console.WriteLine("\t1. Creates a table with partition: year and sort:title."); Console.WriteLine("\t2. Adds a single movie to the table."); Console.WriteLine("\t3. Adds movies to the table from moviedata.json."); Console.WriteLine("\t4. Updates the rating and plot of the movie that was just added."); Console.WriteLine("\t5. Gets a movie using its key (partition + sort)."); Console.WriteLine("\t6. Deletes a movie."); Console.WriteLine("\t7. Uses QueryAsync to return all movies released in a given year."); Console.WriteLine("\t8. Uses ScanAsync to return all movies released within a range of years."); Console.WriteLine("\t9. Finally, it deletes the table that was just created."); WaitForEnter(); } /// <summary> /// Simple method to wait for the Enter key to be pressed. /// </summary> private static void WaitForEnter() { if (IsInteractive) { Console.WriteLine("\nPress <Enter> to continue."); Console.WriteLine(SepBar); _ = Console.ReadLine(); } } }
Crea una tabla para contener los datos de las películas.
/// <summary> /// Creates a new Amazon DynamoDB table and then waits for the new /// table to become active. /// </summary> /// <param name="tableName">The name of the table to create.</param> /// <returns>A Boolean value indicating the success of the operation.</returns> public async Task<bool> CreateMovieTableAsync(string tableName) { try { var response = await _amazonDynamoDB.CreateTableAsync(new CreateTableRequest { TableName = tableName, AttributeDefinitions = new List<AttributeDefinition>() { new AttributeDefinition { AttributeName = "title", AttributeType = ScalarAttributeType.S, }, new AttributeDefinition { AttributeName = "year", AttributeType = ScalarAttributeType.N, }, }, KeySchema = new List<KeySchemaElement>() { new KeySchemaElement { AttributeName = "year", KeyType = KeyType.HASH, }, new KeySchemaElement { AttributeName = "title", KeyType = KeyType.RANGE, }, }, BillingMode = BillingMode.PAY_PER_REQUEST, }); // Wait until the table is ACTIVE and then report success. Console.Write("Waiting for table to become active..."); var request = new DescribeTableRequest { TableName = response.TableDescription.TableName, }; TableStatus status; int sleepDuration = 2000; do { Thread.Sleep(sleepDuration); var describeTableResponse = await _amazonDynamoDB.DescribeTableAsync(request); status = describeTableResponse.Table.TableStatus; Console.Write("."); } while (status != "ACTIVE"); return status == TableStatus.ACTIVE; } catch (ResourceInUseException ex) { Console.WriteLine($"Table {tableName} already exists. {ex.Message}"); throw; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while creating table {tableName}. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while creating table {tableName}. {ex.Message}"); throw; } }
Agrega una sola película a la tabla.
/// <summary> /// Adds a new item to the table. /// </summary> /// <param name="newMovie">A Movie object containing informtation for /// the movie to add to the table.</param> /// <param name="tableName">The name of the table where the item will be added.</param> /// <returns>A Boolean value that indicates the results of adding the item.</returns> public async Task<bool> PutItemAsync(Movie newMovie, string tableName) { try { var item = new Dictionary<string, AttributeValue> { ["title"] = new AttributeValue { S = newMovie.Title }, ["year"] = new AttributeValue { N = newMovie.Year.ToString() }, }; var request = new PutItemRequest { TableName = tableName, Item = item, }; await _amazonDynamoDB.PutItemAsync(request); return true; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found. {ex.Message}"); return false; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while putting item. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while putting item. {ex.Message}"); throw; } }
Actualiza un solo elemento de una tabla.
/// <summary> /// Updates an existing item in the movies table. /// </summary> /// <param name="newMovie">A Movie object containing information for /// the movie to update.</param> /// <param name="newInfo">A MovieInfo object that contains the /// information that will be changed.</param> /// <param name="tableName">The name of the table that contains the movie.</param> /// <returns>A Boolean value that indicates the success of the operation.</returns> public async Task<bool> UpdateItemAsync( Movie newMovie, MovieInfo newInfo, string tableName) { try { var key = new Dictionary<string, AttributeValue> { ["title"] = new AttributeValue { S = newMovie.Title }, ["year"] = new AttributeValue { N = newMovie.Year.ToString() }, }; var updates = new Dictionary<string, AttributeValueUpdate> { ["info.plot"] = new AttributeValueUpdate { Action = AttributeAction.PUT, Value = new AttributeValue { S = newInfo.Plot }, }, ["info.rating"] = new AttributeValueUpdate { Action = AttributeAction.PUT, Value = new AttributeValue { N = newInfo.Rank.ToString() }, }, }; var request = new UpdateItemRequest { AttributeUpdates = updates, Key = key, TableName = tableName, }; await _amazonDynamoDB.UpdateItemAsync(request); return true; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} or item was not found. {ex.Message}"); return false; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while updating item. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while updating item. {ex.Message}"); throw; } }
Recupera un solo elemento de la tabla de películas.
/// <summary> /// Gets information about an existing movie from the table. /// </summary> /// <param name="newMovie">A Movie object containing information about /// the movie to retrieve.</param> /// <param name="tableName">The name of the table containing the movie.</param> /// <returns>A Dictionary object containing information about the item /// retrieved.</returns> public async Task<Dictionary<string, AttributeValue>> GetItemAsync(Movie newMovie, string tableName) { try { var key = new Dictionary<string, AttributeValue> { ["title"] = new AttributeValue { S = newMovie.Title }, ["year"] = new AttributeValue { N = newMovie.Year.ToString() }, }; var request = new GetItemRequest { Key = key, TableName = tableName, }; var response = await _amazonDynamoDB.GetItemAsync(request); return response.Item; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found. {ex.Message}"); return new Dictionary<string, AttributeValue>(); } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while getting item. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while getting item. {ex.Message}"); throw; } }
Escribe un lote de elementos en la tabla de películas.
/// <summary> /// Loads the contents of a JSON file into a list of movies to be /// added to the DynamoDB table. /// </summary> /// <param name="movieFileName">The name of the JSON file.</param> /// <returns>A generic list of movie objects.</returns> public List<Movie> ImportMovies(string movieFileName) { var moviesList = new List<Movie>(); if (!File.Exists(movieFileName)) { return moviesList; } using var sr = new StreamReader(movieFileName); string json = sr.ReadToEnd(); var allMovies = JsonSerializer.Deserialize<List<Movie>>( json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); // Now return the first 250 entries. if (allMovies != null && allMovies.Any()) { moviesList = allMovies.GetRange(0, 250); } return moviesList; } /// <summary> /// Writes 250 items to the movie table. /// </summary> /// <param name="movieFileName">A string containing the full path to /// the JSON file containing movie data.</param> /// <param name="tableName">The name of the table to write items to.</param> /// <returns>A long integer value representing the number of movies /// imported from the JSON file.</returns> public async Task<long> BatchWriteItemsAsync( string movieFileName, string tableName) { try { var movies = ImportMovies(movieFileName); if (!movies.Any()) { Console.WriteLine("Couldn't find the JSON file with movie data."); return 0; } var context = new DynamoDBContextBuilder() // Optional call to provide a specific instance of IAmazonDynamoDB .WithDynamoDBClient(() => _amazonDynamoDB) .Build(); var movieBatch = context.CreateBatchWrite<Movie>( new BatchWriteConfig() { OverrideTableName = tableName }); movieBatch.AddPutItems(movies); Console.WriteLine("Adding imported movies to the table."); await movieBatch.ExecuteAsync(); return movies.Count; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table was not found during batch write operation. {ex.Message}"); throw; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred during batch write operation. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred during batch write operation. {ex.Message}"); throw; } }
Elimina un solo elemento de la tabla.
/// <summary> /// Deletes a single item from a DynamoDB table. /// </summary> /// <param name="tableName">The name of the table from which the item /// will be deleted.</param> /// <param name="movieToDelete">A movie object containing the title and /// year of the movie to delete.</param> /// <returns>A Boolean value indicating the success or failure of the /// delete operation.</returns> public async Task<bool> DeleteItemAsync( string tableName, Movie movieToDelete) { try { var key = new Dictionary<string, AttributeValue> { ["title"] = new AttributeValue { S = movieToDelete.Title }, ["year"] = new AttributeValue { N = movieToDelete.Year.ToString() }, }; var request = new DeleteItemRequest { TableName = tableName, Key = key, }; await _amazonDynamoDB.DeleteItemAsync(request); return true; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found. {ex.Message}"); return false; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while deleting item. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while deleting item. {ex.Message}"); throw; } }
Consulta en la tabla las películas estrenadas en un año determinado.
/// <summary> /// Queries the table for movies released in a particular year and /// then displays the information for the movies returned. /// </summary> /// <param name="tableName">The name of the table to query.</param> /// <param name="year">The release year for which we want to /// view movies.</param> /// <returns>The number of movies that match the query.</returns> public async Task<int> QueryMoviesAsync(string tableName, int year) { try { var movieTable = new TableBuilder(_amazonDynamoDB, tableName) .AddHashKey("year", DynamoDBEntryType.Numeric) .AddRangeKey("title", DynamoDBEntryType.String) .Build(); var filter = new QueryFilter("year", QueryOperator.Equal, year); Console.WriteLine("\nFind movies released in: {year}:"); var config = new QueryOperationConfig() { Limit = 10, // 10 items per page. Select = SelectValues.SpecificAttributes, AttributesToGet = new List<string> { "title", "year", }, ConsistentRead = true, Filter = filter, }; // Value used to track how many movies match the // supplied criteria. var moviesFound = 0; var search = movieTable.Query(config); do { var movieList = await search.GetNextSetAsync(); moviesFound += movieList.Count; foreach (var movie in movieList) { DisplayDocument(movie); } } while (!search.IsDone); return moviesFound; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found. {ex.Message}"); return 0; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while querying movies. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while querying movies. {ex.Message}"); throw; } }
Busca en la tabla películas que se hayan estrenado en un intervalo de años.
/// <summary> /// Scans the table for movies released between the specified years. /// </summary> /// <param name="tableName">The name of the table to scan.</param> /// <param name="startYear">The starting year for the range.</param> /// <param name="endYear">The ending year for the range.</param> /// <returns>The number of movies found in the specified year range.</returns> public async Task<int> ScanTableAsync( string tableName, int startYear, int endYear) { try { var request = new ScanRequest { TableName = tableName, ExpressionAttributeNames = new Dictionary<string, string> { { "#yr", "year" }, }, ExpressionAttributeValues = new Dictionary<string, AttributeValue> { { ":y_a", new AttributeValue { N = startYear.ToString() } }, { ":y_z", new AttributeValue { N = endYear.ToString() } }, }, FilterExpression = "#yr between :y_a and :y_z", ProjectionExpression = "#yr, title, info.actors[0], info.directors, info.running_time_secs", Limit = 10 // Set a limit to demonstrate using the LastEvaluatedKey. }; // Keep track of how many movies were found. int foundCount = 0; var response = new ScanResponse(); do { response = await _amazonDynamoDB.ScanAsync(request); foundCount += response.Items.Count; response.Items.ForEach(i => DisplayItem(i)); request.ExclusiveStartKey = response.LastEvaluatedKey; } while (response?.LastEvaluatedKey?.Count > 0); return foundCount; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found. {ex.Message}"); return 0; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while scanning table. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while scanning table. {ex.Message}"); throw; } }
Elimina la tabla de películas.
/// <summary> /// Deletes a DynamoDB table. /// </summary> /// <param name="tableName">The name of the table to delete.</param> /// <returns>A Boolean value indicating the success of the operation.</returns> public async Task<bool> DeleteTableAsync(string tableName) { try { var request = new DeleteTableRequest { TableName = tableName, }; var response = await _amazonDynamoDB.DeleteTableAsync(request); Console.WriteLine($"Table {response.TableDescription.TableName} successfully deleted."); return true; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found and cannot be deleted. {ex.Message}"); return false; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while deleting table {tableName}. {ex.Message}"); return false; } catch (Exception ex) { Console.WriteLine($"An error occurred while deleting table {tableName}. {ex.Message}"); return false; } }
-
Para obtener información sobre la API, consulte los siguientes temas en la referencia de la API de AWS SDK para .NET .
-
Acciones
En el siguiente ejemplo de código, se muestra cómo utilizar BatchWriteItem
.
- SDK para .NET (v4)
-
nota
Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. Escribe un lote de elementos en la tabla de películas.
/// <summary> /// Loads the contents of a JSON file into a list of movies to be /// added to the DynamoDB table. /// </summary> /// <param name="movieFileName">The name of the JSON file.</param> /// <returns>A generic list of movie objects.</returns> public List<Movie> ImportMovies(string movieFileName) { var moviesList = new List<Movie>(); if (!File.Exists(movieFileName)) { return moviesList; } using var sr = new StreamReader(movieFileName); string json = sr.ReadToEnd(); var allMovies = JsonSerializer.Deserialize<List<Movie>>( json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); // Now return the first 250 entries. if (allMovies != null && allMovies.Any()) { moviesList = allMovies.GetRange(0, 250); } return moviesList; } /// <summary> /// Writes 250 items to the movie table. /// </summary> /// <param name="movieFileName">A string containing the full path to /// the JSON file containing movie data.</param> /// <param name="tableName">The name of the table to write items to.</param> /// <returns>A long integer value representing the number of movies /// imported from the JSON file.</returns> public async Task<long> BatchWriteItemsAsync( string movieFileName, string tableName) { try { var movies = ImportMovies(movieFileName); if (!movies.Any()) { Console.WriteLine("Couldn't find the JSON file with movie data."); return 0; } var context = new DynamoDBContextBuilder() // Optional call to provide a specific instance of IAmazonDynamoDB .WithDynamoDBClient(() => _amazonDynamoDB) .Build(); var movieBatch = context.CreateBatchWrite<Movie>( new BatchWriteConfig() { OverrideTableName = tableName }); movieBatch.AddPutItems(movies); Console.WriteLine("Adding imported movies to the table."); await movieBatch.ExecuteAsync(); return movies.Count; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table was not found during batch write operation. {ex.Message}"); throw; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred during batch write operation. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred during batch write operation. {ex.Message}"); throw; } }
-
Para obtener más información sobre la API, consulta BatchWriteItemla Referencia AWS SDK para .NET de la API.
-
En el siguiente ejemplo de código, se muestra cómo utilizar CreateTable
.
- SDK para .NET (v4)
-
nota
Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. /// <summary> /// Creates a new Amazon DynamoDB table and then waits for the new /// table to become active. /// </summary> /// <param name="tableName">The name of the table to create.</param> /// <returns>A Boolean value indicating the success of the operation.</returns> public async Task<bool> CreateMovieTableAsync(string tableName) { try { var response = await _amazonDynamoDB.CreateTableAsync(new CreateTableRequest { TableName = tableName, AttributeDefinitions = new List<AttributeDefinition>() { new AttributeDefinition { AttributeName = "title", AttributeType = ScalarAttributeType.S, }, new AttributeDefinition { AttributeName = "year", AttributeType = ScalarAttributeType.N, }, }, KeySchema = new List<KeySchemaElement>() { new KeySchemaElement { AttributeName = "year", KeyType = KeyType.HASH, }, new KeySchemaElement { AttributeName = "title", KeyType = KeyType.RANGE, }, }, BillingMode = BillingMode.PAY_PER_REQUEST, }); // Wait until the table is ACTIVE and then report success. Console.Write("Waiting for table to become active..."); var request = new DescribeTableRequest { TableName = response.TableDescription.TableName, }; TableStatus status; int sleepDuration = 2000; do { Thread.Sleep(sleepDuration); var describeTableResponse = await _amazonDynamoDB.DescribeTableAsync(request); status = describeTableResponse.Table.TableStatus; Console.Write("."); } while (status != "ACTIVE"); return status == TableStatus.ACTIVE; } catch (ResourceInUseException ex) { Console.WriteLine($"Table {tableName} already exists. {ex.Message}"); throw; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while creating table {tableName}. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while creating table {tableName}. {ex.Message}"); throw; } }
-
Para obtener más información sobre la API, consulta CreateTablela Referencia AWS SDK para .NET de la API.
-
En el siguiente ejemplo de código, se muestra cómo utilizar DeleteItem
.
- SDK para .NET (v4)
-
nota
Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. /// <summary> /// Deletes a single item from a DynamoDB table. /// </summary> /// <param name="tableName">The name of the table from which the item /// will be deleted.</param> /// <param name="movieToDelete">A movie object containing the title and /// year of the movie to delete.</param> /// <returns>A Boolean value indicating the success or failure of the /// delete operation.</returns> public async Task<bool> DeleteItemAsync( string tableName, Movie movieToDelete) { try { var key = new Dictionary<string, AttributeValue> { ["title"] = new AttributeValue { S = movieToDelete.Title }, ["year"] = new AttributeValue { N = movieToDelete.Year.ToString() }, }; var request = new DeleteItemRequest { TableName = tableName, Key = key, }; await _amazonDynamoDB.DeleteItemAsync(request); return true; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found. {ex.Message}"); return false; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while deleting item. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while deleting item. {ex.Message}"); throw; } }
-
Para obtener más información sobre la API, consulta DeleteItemla Referencia AWS SDK para .NET de la API.
-
En el siguiente ejemplo de código, se muestra cómo utilizar DeleteTable
.
- SDK para .NET (v4)
-
nota
Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. /// <summary> /// Deletes a DynamoDB table. /// </summary> /// <param name="tableName">The name of the table to delete.</param> /// <returns>A Boolean value indicating the success of the operation.</returns> public async Task<bool> DeleteTableAsync(string tableName) { try { var request = new DeleteTableRequest { TableName = tableName, }; var response = await _amazonDynamoDB.DeleteTableAsync(request); Console.WriteLine($"Table {response.TableDescription.TableName} successfully deleted."); return true; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found and cannot be deleted. {ex.Message}"); return false; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while deleting table {tableName}. {ex.Message}"); return false; } catch (Exception ex) { Console.WriteLine($"An error occurred while deleting table {tableName}. {ex.Message}"); return false; } }
-
Para obtener más información sobre la API, consulta DeleteTablela Referencia AWS SDK para .NET de la API.
-
En el siguiente ejemplo de código, se muestra cómo utilizar GetItem
.
- SDK para .NET (v4)
-
nota
Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. /// <summary> /// Gets information about an existing movie from the table. /// </summary> /// <param name="newMovie">A Movie object containing information about /// the movie to retrieve.</param> /// <param name="tableName">The name of the table containing the movie.</param> /// <returns>A Dictionary object containing information about the item /// retrieved.</returns> public async Task<Dictionary<string, AttributeValue>> GetItemAsync(Movie newMovie, string tableName) { try { var key = new Dictionary<string, AttributeValue> { ["title"] = new AttributeValue { S = newMovie.Title }, ["year"] = new AttributeValue { N = newMovie.Year.ToString() }, }; var request = new GetItemRequest { Key = key, TableName = tableName, }; var response = await _amazonDynamoDB.GetItemAsync(request); return response.Item; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found. {ex.Message}"); return new Dictionary<string, AttributeValue>(); } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while getting item. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while getting item. {ex.Message}"); throw; } }
-
Para obtener más información sobre la API, consulta GetItemla Referencia AWS SDK para .NET de la API.
-
En el siguiente ejemplo de código, se muestra cómo utilizar PutItem
.
- SDK para .NET (v4)
-
nota
Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. /// <summary> /// Adds a new item to the table. /// </summary> /// <param name="newMovie">A Movie object containing informtation for /// the movie to add to the table.</param> /// <param name="tableName">The name of the table where the item will be added.</param> /// <returns>A Boolean value that indicates the results of adding the item.</returns> public async Task<bool> PutItemAsync(Movie newMovie, string tableName) { try { var item = new Dictionary<string, AttributeValue> { ["title"] = new AttributeValue { S = newMovie.Title }, ["year"] = new AttributeValue { N = newMovie.Year.ToString() }, }; var request = new PutItemRequest { TableName = tableName, Item = item, }; await _amazonDynamoDB.PutItemAsync(request); return true; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found. {ex.Message}"); return false; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while putting item. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while putting item. {ex.Message}"); throw; } }
-
Para obtener más información sobre la API, consulta PutItemla Referencia AWS SDK para .NET de la API.
-
En el siguiente ejemplo de código, se muestra cómo utilizar Query
.
- SDK para .NET (v4)
-
nota
Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. /// <summary> /// Queries the table for movies released in a particular year and /// then displays the information for the movies returned. /// </summary> /// <param name="tableName">The name of the table to query.</param> /// <param name="year">The release year for which we want to /// view movies.</param> /// <returns>The number of movies that match the query.</returns> public async Task<int> QueryMoviesAsync(string tableName, int year) { try { var movieTable = new TableBuilder(_amazonDynamoDB, tableName) .AddHashKey("year", DynamoDBEntryType.Numeric) .AddRangeKey("title", DynamoDBEntryType.String) .Build(); var filter = new QueryFilter("year", QueryOperator.Equal, year); Console.WriteLine("\nFind movies released in: {year}:"); var config = new QueryOperationConfig() { Limit = 10, // 10 items per page. Select = SelectValues.SpecificAttributes, AttributesToGet = new List<string> { "title", "year", }, ConsistentRead = true, Filter = filter, }; // Value used to track how many movies match the // supplied criteria. var moviesFound = 0; var search = movieTable.Query(config); do { var movieList = await search.GetNextSetAsync(); moviesFound += movieList.Count; foreach (var movie in movieList) { DisplayDocument(movie); } } while (!search.IsDone); return moviesFound; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found. {ex.Message}"); return 0; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while querying movies. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while querying movies. {ex.Message}"); throw; } }
-
Para obtener información sobre la API, consulte Query en la referencia de la API de AWS SDK para .NET .
-
En el siguiente ejemplo de código, se muestra cómo utilizar Scan
.
- SDK para .NET (v4)
-
nota
Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. /// <summary> /// Scans the table for movies released between the specified years. /// </summary> /// <param name="tableName">The name of the table to scan.</param> /// <param name="startYear">The starting year for the range.</param> /// <param name="endYear">The ending year for the range.</param> /// <returns>The number of movies found in the specified year range.</returns> public async Task<int> ScanTableAsync( string tableName, int startYear, int endYear) { try { var request = new ScanRequest { TableName = tableName, ExpressionAttributeNames = new Dictionary<string, string> { { "#yr", "year" }, }, ExpressionAttributeValues = new Dictionary<string, AttributeValue> { { ":y_a", new AttributeValue { N = startYear.ToString() } }, { ":y_z", new AttributeValue { N = endYear.ToString() } }, }, FilterExpression = "#yr between :y_a and :y_z", ProjectionExpression = "#yr, title, info.actors[0], info.directors, info.running_time_secs", Limit = 10 // Set a limit to demonstrate using the LastEvaluatedKey. }; // Keep track of how many movies were found. int foundCount = 0; var response = new ScanResponse(); do { response = await _amazonDynamoDB.ScanAsync(request); foundCount += response.Items.Count; response.Items.ForEach(i => DisplayItem(i)); request.ExclusiveStartKey = response.LastEvaluatedKey; } while (response?.LastEvaluatedKey?.Count > 0); return foundCount; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} was not found. {ex.Message}"); return 0; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while scanning table. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while scanning table. {ex.Message}"); throw; } }
-
Para obtener información sobre la API, consulte Scan en la referencia de la API de AWS SDK para .NET .
-
En el siguiente ejemplo de código, se muestra cómo utilizar UpdateItem
.
- SDK para .NET (v4)
-
nota
Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. /// <summary> /// Updates an existing item in the movies table. /// </summary> /// <param name="newMovie">A Movie object containing information for /// the movie to update.</param> /// <param name="newInfo">A MovieInfo object that contains the /// information that will be changed.</param> /// <param name="tableName">The name of the table that contains the movie.</param> /// <returns>A Boolean value that indicates the success of the operation.</returns> public async Task<bool> UpdateItemAsync( Movie newMovie, MovieInfo newInfo, string tableName) { try { var key = new Dictionary<string, AttributeValue> { ["title"] = new AttributeValue { S = newMovie.Title }, ["year"] = new AttributeValue { N = newMovie.Year.ToString() }, }; var updates = new Dictionary<string, AttributeValueUpdate> { ["info.plot"] = new AttributeValueUpdate { Action = AttributeAction.PUT, Value = new AttributeValue { S = newInfo.Plot }, }, ["info.rating"] = new AttributeValueUpdate { Action = AttributeAction.PUT, Value = new AttributeValue { N = newInfo.Rank.ToString() }, }, }; var request = new UpdateItemRequest { AttributeUpdates = updates, Key = key, TableName = tableName, }; await _amazonDynamoDB.UpdateItemAsync(request); return true; } catch (ResourceNotFoundException ex) { Console.WriteLine($"Table {tableName} or item was not found. {ex.Message}"); return false; } catch (AmazonDynamoDBException ex) { Console.WriteLine($"An Amazon DynamoDB error occurred while updating item. {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"An error occurred while updating item. {ex.Message}"); throw; } }
-
Para obtener más información sobre la API, consulta UpdateItemla Referencia AWS SDK para .NET de la API.
-