Amazon DynamoDB
开发人员指南 (API 版本 2012-08-10)
AWS 文档中描述的 AWS 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 Amazon AWS 入门

步骤 7:尝试有条件地删除电影

Microsoft .NET 和 DynamoDB 教程的本步骤中,您尝试使用某个未满足的条件删除电影记录,该删除失败了。然后,在更改该条件以满足它后,该删除成功了。

DynamoDB_intro 中的 Main 函数首先按下面所示创建一个条件:

Expression condition = new Expression(); condition.ExpressionAttributeValues[":val"] = 5.0; condition.ExpressionStatement = "info.rating <= :val";

Main 函数随后将 Expression 作为 DeletingItem_async 的参数之一传递,然后等待它。DeletingItem_async07_DeletingItem.cs 文件中实施:

using System; using System.Threading.Tasks; using Amazon.DynamoDBv2.DocumentModel; namespace DynamoDB_intro { public static partial class Ddb_Intro { /*-------------------------------------------------------------------------- * DeletingItem_async *--------------------------------------------------------------------------*/ public static async Task<bool> DeletingItem_async( Table table, int year, string title, Expression condition=null ) { Document deletedItem = null; operationSucceeded = false; operationFailed = false; // Create Primitives for the HASH and RANGE portions of the primary key Primitive hash = new Primitive(year.ToString(), true); Primitive range = new Primitive(title, false); DeleteItemOperationConfig deleteConfig = new DeleteItemOperationConfig( ); deleteConfig.ConditionalExpression = condition; deleteConfig.ReturnValues = ReturnValues.AllOldAttributes; Console.WriteLine( " -- Trying to delete the {0} movie \"{1}\"...", year, title ); try { Task<Document> delItem = table.DeleteItemAsync( hash, range, deleteConfig ); deletedItem = await delItem; } catch( Exception ex ) { Console.WriteLine( " FAILED to delete the movie item, for this reason:\n {0}\n", ex.Message ); operationFailed = true; return ( false ); } Console.WriteLine( " -- SUCCEEDED in deleting the movie record that looks like this:\n" + deletedItem.ToJsonPretty( ) ); operationSucceeded = true; return ( true ); } } }

DeletingItem_async 转而将条件 Expression 包含在 DeletingItem_async 在等待 Expression 时传递到 DynamoDB Table.DeleteItemAsync 方法的 DeleteItemOperationConfig 对象中:

由于电影的评分是 6.5,高于 5.0,未满足条件,因此删除失败。

然后,当 Main 函数将条件中的评分阈值更改为 7.0 而不是 5.0 时,删除将成功。

下一步

步骤 8:查询 Movies 表

本页内容: