无法在 C# 的 dynamoDb 中使用 GetItem()

问题描述 投票:0回答:3

我想使用 C# 从 DYnamodb 表中获取项目

这是我的方法

public static dynamic Dynamodb() {
            string region = "us-east-2";
            string tableName = "RetailTestData";
            var credentials = new BasicAWSCredentials(Environment.GetEnvironmentVariable("awsAccessKeyId"), Environment.GetEnvironmentVariable("awsSecretAccessKey"));
            var client = new AmazonDynamoDBClient(credentials, RegionEndpoint.GetBySystemName(region));
            var table = Table.LoadTable(client, tableName);
             var item=table.GetItem();
return item;
}

参考资料取自 从 DynamoDB 表中获取 JSON 格式的数据

但是当我尝试使用代码时出现错误

最后我希望使用

item.ToJson()
方法,因为我的代码的其余部分使用 json 方法

amazon-web-services amazon-dynamodb
3个回答
1
投票

这对我有用:

using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DocumentModel;

AmazonDynamoDBClient client = new AmazonDynamoDBClient();

Table table = Table.LoadTable(client, "test");
string pk = "123";

Document document = table.GetItem(pk);


0
投票

要从 Amazon DynamoDB 获取项目,请尝试使用 AWS SDK for .NET V3(这是 .NET SDK 的推荐版本)。

您可以使用 GetItemAsync()。请注意,该调用是异步方法。如果您不熟悉 AWS SDK For .NET V3 - 这里是开发指南。

什么是适用于 .NET 的 AWS 开发工具包

C#代码是:

public static async Task<Dictionary<string, AttributeValue>> GetItemAsync(AmazonDynamoDBClient client, Movie newMovie, string tableName)
        {
            var key = new Dictionary<string, AttributeValue>
            {
                ["title"] = new AttributeValue { S = newMovie.Title },
                ["year"] = new AttributeValue { N = newMovie.Year.ToString() },
            };

            var request = new GetItemRequest
            {
                Key = key,
                TableName = tableName,
            };

            var response = await client.GetItemAsync(request);
            return response.Item;
        }

此示例和其他 C# 示例位于官方 AWS 代码库


0
投票

这个问题有点晚了,但我打算添加一些有关密钥和文档的澄清位,但 @Leeroy Hannigans 的答案可以完成这项工作。

我正在使用此处找到的文档: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItemsDocumentClasses.html

using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DocumentModel;

AmazonDynamoDBClient client = new AmazonDynamoDBClient();


Table table = Table.LoadTable(client, "Music");

// You can construct you keys however you want/need to
// This just has a primary key of Music with a sort key 
// of {songName} there are other ways to construct a key,
// for this example
Primitive primaryKey = "Tenacious D"; // this is also a string
Primitive sortKey = "Tribute" // This is just a string

Document document = table.GetItem(primaryKey, sortKey);
return document.ToJson(); // converts the item to a JSON object

下面是上面示例的视觉布局

© www.soinside.com 2019 - 2024. All rights reserved.