Tools: String Manipulations Find Dupes My IP Json Formatter Lorem Ipsum More...
Discussion Options
ajax animation

.NET Core: AWS DynamoDb - List Items by Primary Key (PK/HASH) Thats has a Sort Key RANGE

10/25/2017 7:04:10 PM by: CodeLocker

The following can be used to LIST items from a DynamoDb table based on the Primary Key. This is useful if you have a composite KEY that uses a HASH and RANGE. In this code, we are passing the the HASH (AccountId).

View Copy: Content Copied
//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<List<Entities.User>> List__Async(long accountId)
{
	var items = new List<Entities.User>();
	if (accountId == 0)
	{
		return items;
	}

	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 });

		//list the users from dynamodb
		AsyncSearch<Entities.User> query = dbContext.QueryAsync<Entities.User>(accountId);

		while (query.IsDone == false)
		{
			items.AddRange(await query.GetNextSetAsync());
		}
	}
	catch (Exception ex)
	{
	}

	return items;
}
Copy: Content Copied
ajax animation
×

Get Coding

Store your first code or add more code to your collection.
You must login to report abuse. ×