Search code examples
c#amazon-web-servicesamazon-dynamodb

AWS dynamodb can't update item using .net api


when I update item using .net api, it always say 'The provided key element does not match the schema' this is my code:

    try
{
    var dic = new Dictionary<string, AttributeValue>()
    {
        { "report_id",new AttributeValue(){ S="isYCga2laNFnjJzz"} },
        { "time_report",new AttributeValue(){ N="0"} }
    };
    await client.UpdateItemAsync("project8_Dev_user_report", dic, null);
}
catch (Exception e)
{
    Debug.LogError(e);
}

and my database look like:enter image description here

PS: this is my table schema enter image description here


Solution

  • Your parameters for UpdateItem are wrong. It should be something similar to this:

    AmazonDynamoDBClient client = new AmazonDynamoDBClient();
    string tableName = "ProductCatalog";
    
    var request = new UpdateItemRequest
    {
        TableName = tableName,
        Key = new Dictionary<string,AttributeValue>() { { "Id", new AttributeValue { N = "202" } } },
        ExpressionAttributeNames = new Dictionary<string,string>()
        {
            {"#A", "Authors"},
            {"#P", "Price"},
            {"#NA", "NewAttribute"},
            {"#I", "ISBN"}
        },
        ExpressionAttributeValues = new Dictionary<string, AttributeValue>()
        {
            {":auth",new AttributeValue { SS = {"Author YY","Author ZZ"}}},
            {":p",new AttributeValue {N = "1"}},
            {":newattr",new AttributeValue {S = "someValue"}},
        },
    
        // This expression does the following:
        // 1) Adds two new authors to the list
        // 2) Reduces the price
        // 3) Adds a new attribute to the item
        // 4) Removes the ISBN attribute from the item
        UpdateExpression = "ADD #A :auth SET #P = #P - :p, #NA = :newattr REMOVE #I"
    };
    var response = client.UpdateItem(request);
    

    It should contain a Key and an UpdateExression at a minimum.