的版本 4 (V4) 适用于 .NET 的 AWS SDK 已经发布!
有关重大更改和迁移应用程序的信息,请参阅迁移主题。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
使用 (v4) 的 DynamoDB 示例 适用于 .NET 的 SDK
以下代码示例向您展示了如何使用带有 DynamoDB 的 适用于 .NET 的 AWS SDK (v4) 来执行操作和实现常见场景。
基础知识是向您展示如何在服务中执行基本操作的代码示例。
操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景的上下文查看操作。
每个示例都包含一个指向完整源代码的链接,您可以从中找到有关如何在上下文中设置和运行代码的说明。
开始使用
以下代码示例演示如何开始使用 DynamoDB。
- 适用于 .NET 的 SDK (v4)
-
注意
还有更多相关信息 GitHub。在 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}"); } } }
-
有关 API 的详细信息,请参阅 适用于 .NET 的 AWS SDK API 参考ListTables中的。
-
基本功能
以下代码示例展示了如何:
创建可保存电影数据的表。
在表中加入单一电影,获取并更新此电影。
向 JSON 示例文件的表中写入电影数据。
查询在给定年份发行的电影。
扫描在年份范围内发行的电影。
删除表中的电影后再删除表。
- 适用于 .NET 的 SDK (v4)
-
注意
还有更多相关信息 GitHub。在 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(); } } }
创建一个包含影片数据的表。
/// <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; } }
将单个影片添加到表中。
/// <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; } }
更新表中的单个项目。
/// <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; } }
从影片表中检索单个项目。
/// <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; } }
将一批项目写入影片表。
/// <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; } }
从表中删除单个项目。
/// <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; } }
查询表中是否有特定年份发行的影片。
/// <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; } }
扫描此表以查找几年内发行的影片。
/// <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; } }
删除影片表。
/// <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; } }
-
有关 API 详细信息,请参阅《适用于 .NET 的 AWS SDK API 参考》中的以下主题。
-
操作
以下代码示例演示了如何使用 BatchWriteItem
。
- 适用于 .NET 的 SDK (v4)
-
注意
还有更多相关信息 GitHub。在 AWS 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 将一批项目写入影片表。
/// <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; } }
-
有关 API 的详细信息,请参阅 适用于 .NET 的 AWS SDK API 参考BatchWriteItem中的。
-
以下代码示例演示了如何使用 CreateTable
。
- 适用于 .NET 的 SDK (v4)
-
注意
还有更多相关信息 GitHub。在 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; } }
-
有关 API 的详细信息,请参阅 适用于 .NET 的 AWS SDK API 参考CreateTable中的。
-
以下代码示例演示了如何使用 DeleteItem
。
- 适用于 .NET 的 SDK (v4)
-
注意
还有更多相关信息 GitHub。在 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; } }
-
有关 API 的详细信息,请参阅 适用于 .NET 的 AWS SDK API 参考DeleteItem中的。
-
以下代码示例演示了如何使用 DeleteTable
。
- 适用于 .NET 的 SDK (v4)
-
注意
还有更多相关信息 GitHub。在 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; } }
-
有关 API 的详细信息,请参阅 适用于 .NET 的 AWS SDK API 参考DeleteTable中的。
-
以下代码示例演示了如何使用 GetItem
。
- 适用于 .NET 的 SDK (v4)
-
注意
还有更多相关信息 GitHub。在 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; } }
-
有关 API 的详细信息,请参阅 适用于 .NET 的 AWS SDK API 参考GetItem中的。
-
以下代码示例演示了如何使用 PutItem
。
- 适用于 .NET 的 SDK (v4)
-
注意
还有更多相关信息 GitHub。在 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; } }
-
有关 API 的详细信息,请参阅 适用于 .NET 的 AWS SDK API 参考PutItem中的。
-
以下代码示例演示了如何使用 Query
。
- 适用于 .NET 的 SDK (v4)
-
注意
还有更多相关信息 GitHub。在 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; } }
-
有关 API 详细信息,请参阅《适用于 .NET 的 AWS SDK API 参考》中的 Query。
-
以下代码示例演示了如何使用 Scan
。
- 适用于 .NET 的 SDK (v4)
-
注意
还有更多相关信息 GitHub。在 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; } }
-
有关 API 详细信息,请参阅《适用于 .NET 的 AWS SDK API 参考》中的 Scan。
-
以下代码示例演示了如何使用 UpdateItem
。
- 适用于 .NET 的 SDK (v4)
-
注意
还有更多相关信息 GitHub。在 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; } }
-
有关 API 的详细信息,请参阅 适用于 .NET 的 AWS SDK API 参考UpdateItem中的。
-