Getting started with #DynamoDB in C#

DynamoDB is a good way to get started with NoSQL databases, and being hosted in AWS, means that you don’t have to worry about servers or backups.

Now, a few assumptions before starting. I’m assuming that you’ve set up a test table, with at least item, with primary key called id of type string. I’m also assuming your development machine has stored AWS credentials, (AWS configure), since they won’t be in the code.

So, step 1, we’ll install two NUGET packages;

Install-Package AWSSDK.DynamoDBv2
Install-Package Newtonsoft.Json

Then, we’ll set up a private static reference to our client as follows;

private static readonly AmazonDynamoDBClient Client = new AmazonDynamoDBClient();

The code supplied on Amazon for listing tables is designed to list any number of tables, however, this simplified version will read up to 100 tables. But here is a simplified version;

private static void ListMyTables()
var response = Client.ListTablesAsync().Result;

Now, Imagine we want to read an item from the table, by id and return the data as JSON, we’d use;

private static string GetJsonById(string tableName, string id)
var request = new QueryRequest
TableName = tableName,
KeyConditionExpression = “id = :v_Id”,
ExpressionAttributeValues = new Dictionary<string, AttributeValue> {
{“:v_Id”, new AttributeValue { S = id }}}

var response = Client.QueryAsync(request).Result;

return JsonConvert.SerializeObject(response.Items, Formatting.Indented);

Where we pass the table name, and the id, and it returns as JSON.

And finally, let’s imagine we want to write to the table, with some JSON;

private static void CreateItemFromJson(string tableName, string jsonText)
var item = Document.FromJson(jsonText);
var table = Table.LoadTable(Client, tableName);
var ignore =table.PutItemAsync(item).Result;

And that’s the basic read/write functionality of DynamoDB.

Leave a Reply

Your email address will not be published. Required fields are marked *