The following can be used to GET a single item from a DynamoDb table.
//entity
public class User
{
public long UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
//API
//namespaces
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Amazon;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;
public async Task<Entities.User> Get__Async(long userId)
{
if (userId == 0)
{
return null;
}
try
{
//access key and secret key (should not be hardcoded)
var awsOptions = new Amazon.Extensions.NETCore.Setup.AWSOptions()
{
Credentials = new Amazon.Runtime.BasicAWSCredentials("ACCESS_KEY", "SECRET_KEY"),
Region = Amazon.RegionEndpoint.USEast1
};
//create the client
AmazonDynamoDBClient client = new AmazonDynamoDBClient(awsOptions.Credentials, awsOptions.Region);
//add the table mapping
string tableName = "users";
AWSConfigsDynamoDB.Context.TypeMappings[typeof(Entities.User)] = new Amazon.Util.TypeMapping(typeof(Entities.User), tableName);
//create the db context
DynamoDBContext dbContext = new DynamoDBContext(this._dynamoDBClient, new DynamoDBContextConfig { Conversion = DynamoDBEntryConversion.V2 });
//get the users from dynamodb
return await dbContext.LoadAsync<Entities.User>(userId);
}
catch (Exception ex)
{
}
return null;
}