Store Your Code Now
Tools: String Manipulations Find Dupes My IP Json Formatter Lorem Ipsum More...
Discussion Options

.NET Core: AWS DynamoDb - Get Item by Primary Key (PK/HASH)

10/25/2017 6:58:33 PM by: CodeLocker

The following can be used to GET a single item from a DynamoDb table. 

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<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;
}
Copy: Content Copied
×

Get Coding

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