如何将DynamoDB属性设置为空列表?

时间:2017-01-13 01:03:21

标签: c# amazon-dynamodb aws-sdk

我尝试使用AWS SDK for .NET中的DynamoDBv2库,通过更新请求将DynamoDB文档中的属性设置为空列表。

我尝试了明显的更新表达式,但没有成功:

// Fails, expression attribute values cannot contain an empty list
...
ExpressionAttributeValues = new Dictionary<string, AttributeValue> {
    { ":empty", new AttributeValue { L = new List<AttributeValue> { } } },
},
UpdateExpression = "SET #P.MyList = :empty",
...

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:5)

我在挖掘AWS SDK源代码后找到了答案。关键是memcpy属性是可设置的。这会调用以下代码:

IsLSet

在确定您的AttributeValue是否已初始化时,使用以下代码:

public static void SetIsSet<T>(bool isSet, ref List<T> field)
{
    if (isSet)
        field = new AlwaysSendList<T>(field);
    else
        field = new List<T>();
}

这也说明了使用public static bool GetIsSet<T>(List<T> field) { if (field == null) return false; if (field.Count > 0) return true; var sl = field as AlwaysSendList<T>; if (sl != null) return true; return false; } 没有达到预期效果的原因 - 由于new AttributeValue { L = new List<AttributeValue> { } }为0,此方法将返回false。但是,检查特殊Count如果您设置了AlwaysSendList属性,则type将返回true。

回到你的代码,答案是使用以下内容:

IsLSet

答案 1 :(得分:0)

我自己刚刚遇到了这个问题。看起来至少自 2018 年 11 月 ( https://github.com/aws/aws-sdk-net/issues/1116 ) 以来一直存在的错误。我的解决方法是在设置 IsLSet = true 的值后立即手动设置 L

例如,以下是创建空列表属性的方法:

ExpressionAttributeValues = new Dictionary<string, AttributeValue> 
{
    { ":empty", new AttributeValue { L = new List<AttributeValue>(), IsLSet = true }},
},
UpdateExpression = "SET #P.MyList = :empty",

无论您的列表是否为空,您都应该能够使用上述语法。例如:

ExpressionAttributeValues = new Dictionary<string, AttributeValue> 
{
    { ":MyListOfValues", new AttributeValue { L = listValues, IsLSet = true }},
},
UpdateExpression = "SET #P.MyList = :MyListOfValues",
相关问题