You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS DynamoDB使用.NET API更新Item报错:键元素与架构不匹配

解决DynamoDB更新报错:The provided key element does not match the schema

错误原因

你调用UpdateItemAsync时犯了两个关键错误:

  1. 第二个参数的用途是指定要更新的Item的完整主键,但你把主键和要更新的属性混在了一起传入。
  2. 你的表是复合主键(分区键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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 20:40:14