如何使用 DynamoDBContext 加载和包含排序键?



用dynamodb做实验,我有这样的查询:

var request = new QueryRequest
{
TableName = "vs-configurator-engine-back-table",
KeyConditionExpression = "HashKey = :key and begins_with(SortKey, :sortKey)",
ExpressionAttributeValues = new Dictionary<string, Amazon.DynamoDBv2.Model.AttributeValue>  {
{":key", new Amazon.DynamoDBv2.Model. AttributeValue { S =  key }},
{":sortKey", new Amazon.DynamoDBv2.Model. AttributeValue { S =  sort }},
},
};

where key and sort:

var key = "modelyear#specialParam#Id#year#metadata";
string sort = "ruleset#";

这个工作,但我不喜欢读取数据时,我不得不检索值,如:

response.Items[0].TryGetValue("MyProp", out AttributeValue propOut);

我习惯了。net到Mysql的世界,在那里我可以得到一个对象类,所以我尝试了这种方法:

[DynamoDBTable("myCoolTable")]
public class MyObject
{
[DynamoDBHashKey]
public string HashKey { get; set; }
public string SortKey { get; set; }
[DynamoDBProperty]
public DateTime activeFrom { get; set; }
[DynamoDBProperty]
public Guid id { get; set; }
}
public async Task<DateTime> GetData()
{
AmazonDynamoDBConfig clientConfig = new AmazonDynamoDBConfig();
AmazonDynamoDBClient client = new AmazonDynamoDBClient(clientConfig);
DynamoDBContext context = new DynamoDBContext(client);
MyObject obj = context.Load<MyObject>("modelyear#specialParam#Id#year#metadata");
}

当我这样做,我得到一个错误:

无法转换属性SortKey的范围键值

我正试图找出如何将排序键发送到查询中,但也不太理解错误消息。

我想发送sorkey到查询,但也能够转换它的值一旦它被检索。

Load方法用于从表中检索单个项,因此您需要提供整个主键、散列和范围键。

在幕后,Load方法实际上是从原生AWS DynamoDB API调用GetItem操作。这意味着你不能使用begins_with或任何其他函数。

您需要使用Query,例如:

DynamoDBContext context = new DynamoDBContext(client);
string replyId = "DynamoDB#DynamoDB Thread 1"; //Partition key
DateTime twoWeeksAgoDate = DateTime.UtcNow.Subtract(new TimeSpan(14, 0, 0, 0)); // Date to compare.
IEnumerable<Reply> latestReplies = context.Query<Reply>(replyId, QueryOperator.GreaterThan, twoWeeksAgoDate);

最新更新