AWS DynamoDB使用.NET API更新Item报错:键元素与架构不匹配
解决DynamoDB更新报错:The provided key element does not match the schema
错误原因
你调用UpdateItemAsync时犯了两个关键错误:
- 第二个参数的用途是指定要更新的Item的完整主键,但你把主键和要更新的属性混在了一起传入。
- 你的表是复合主键(分区键
report_id+ 排序键user_id),你只传了分区键,缺少排序键,导致DynamoDB判定主键不符合表结构。
修正后的代码
方式一:使用UpdateItemRequest对象(推荐)
try { // 构造主键:必须包含分区键report_id和排序键user_id,定位要更新的Item var primaryKey = new Dictionary<string, AttributeValue>() { { "report_id", new AttributeValue { S = "isYCga2laNFnjJzz" } }, { "user_id", new AttributeValue { S = "替换为实际的user_id值" } } }; // 构造更新请求,指定要修改的属性 var updateRequest = new UpdateItemRequest { TableName = "project8_Dev_user_report", Key = primaryKey, UpdateExpression = "SET time_report = :newValue", ExpressionAttributeValues = new Dictionary<string, AttributeValue>() { { ":newValue", new AttributeValue { N = "0" } } } }; await client.UpdateItemAsync(updateRequest); } catch (Exception e) { Debug.LogError(e); }
方式二:使用简化重载
try { var primaryKey = new Dictionary<string, AttributeValue>() { { "report_id", new AttributeValue { S = "isYCga2laNFnjJzz" } }, { "user_id", new AttributeValue { S = "替换为实际的user_id值" } } }; var expressionValues = new Dictionary<string, AttributeValue>() { { ":newValue", new AttributeValue { N = "0" } } }; await client.UpdateItemAsync("project8_Dev_user_report", primaryKey, "SET time_report = :newValue", expressionValues, null); } catch (Exception e) { Debug.LogError(e); }
关键注意事项
- 主键必须完整:复合主键需要同时传入分区键和排序键,且类型要和表定义一致(都是字符串类型)。
- 区分主键和更新属性:主键用来定位Item,要修改的属性必须通过
UpdateExpression指定,不能和主键参数混传。
内容的提问来源于stack exchange,提问作者Nguyen Hoai Nam
相关产品推荐
相关产品推荐

