dynobase-icon
Dynobase

21 DynamoDB .NET / C# Query Code Examples

Ravindu Perera

Written by Ravindu Perera

Published on December 25th, 2021

Still using AWS console to work with DynamoDB? 🙈

Time to 10x your DynamoDB productivity with Dynobase [learn more]

DynamoDB is a cloud-hosted NoSQL database from Amazon. It offers dependable performance, a well-managed environment, and easy API access to interact with it.

This article will help you perform various queries in DynamoDB with C#.

If you're looking for similar guide but for Node.js, you can find it here, for Rust, and for Python / boto3 here.

List of DynamoDB C# Query Examples

Setup

To set up the DynamoDB in the .NET environment, you need the AWSSDK.DynamoDBv2 package. It provides a .NET API that facilitates the interactions with DynamoDB to execute different query operations.

For this article's examples, I'm using the Localstack framework. And, the syntax will remain the same for the actual DynamoDB instance by removing the Service URL parameter.

Let's see how to insert a new record and retrieve it back using scanning the table or using a hash key.

Setup the DynamoDB client

You need to pass the accessId and the accessKey to AmazonDynamoDBClient constructor.

Create Table and Model Class

To construct the table, we're building the create table request. We must specify all of the table's declared keys to do so. If you have many tables, this may appear to be a bit of a formality; however, I will demonstrate several alternatives to make this process easier and faster in the future.

There are two unique attributes we can use.

  • DynamoDBTable--- Map DynamoDB equivalent table.
  • DynamoDBHashKey--- Map the table hash key.

Query

DynamoDB allows querying not only on the main table index, but also on LSIs (Local Secondary Indexes) and GSIs (Global Secondary Indexes).

  • SaveOrUpdateEmployee ---To save a new entity, execute SaveAsync. Keep in mind that SaveAsync will create or update the record; if the form already exists, the method execution will override the data on the matching record.
  • GetEmployeeUsingHashKey ---This method will retrieve the records using the hash key.
  • ScanForEmployeeUsingFirstName will scan the whole table and search for the first name.

Delete Table

The DeleteAsync method deletes an item by specifying the partition and range key or using the Item itself.

Delete Item

Low-level Model

Object Persistence Model

You Can map your client-side classes to Amazon DynamoDB tables using the AWS SDK for .Net object persistence mechanism. The Item in the appropriate tables is assigned to each object instance. The DynamoDBContext class, an entry point to DynamoDB, is provided by the object persistence model to save client-side objects to the tables. This class establishes a connection to DynamoDB, allowing you to view tables, execute CRUD actions, and run queries.

We can do the above using the same model, including the table name and partition key.

Prevent Overwriting Existing Records

We need to use conditional expressions in DynamoDB to prevent overrides. If we try to insert a record that already has a hash key in the table, a ConditionalCheckFailedException will be raised.

Scan

By specifying scan criteria, you can filter scan results. Any attribute in the table is used to evaluate the condition. For example, assume you have a client-side class called EmployeeCategory mapped to the DynamoDB employee table. The C# example below searches the table and returns only the employee IDs bigger than 10.

The Scan method returns an IEnumerable collection that has been "lazy-loaded." It returns only one page of results at first and then, if necessary, makes a service request for the following page. You only need to iterate through the IEnumerable to get all matching entries.

Get Items using Query Filter

Object Persistence Model

Low-Level Model

Put Item

Replaces an old item with a new item or creates a new item. If an item with the same primary key already exists in the provided database, the new Item entirely replaces it. You can insert a new item if the provided primary key doesn't exist or return an existing item if it contains particular attribute values.

You can use the returnValues option to return the Item's attribute values in the same action as inserting the Item.

The primary key attribute(s) are the only attributes required when adding an item. Null values are not allowed for attribute values. The length of string and binary type characteristics must be more significant than zero. There can't be any empty set type attributes. ValidationException will be thrown for requests with open values.

PutItem can either return a copy of the old Item (before the update) or a copy of the new Item (after the update).

Get All Items

Let's find all the items on the table.

Get All Items (with Pagination)

The below code will show the functionality of the GetAllEmployees method. First, you need to get the model's table reference and check for a pagination token. You can use the paginationToken with scan option to fetch the following result set.

Get Single Item

Update Item

Batch Get Items

The code below pulls three items from the EmployeeDetails table in C#. The results elements are not necessarily in the same order as the primary keys you selected.

When you try to retrieve multiple items from a database table using one request, you have to consider the following:

  • You need to create an instance of the CreateBatchGet class.
  • We need to specify the primary key list.
  • When you call the Execute method, the response returns the items in the Result property.

Get Items from Multiple Tables

Follow these steps to fetch items from several tables:

  • First, create an instance of the CreateBatchGet type for each type and pass in the primary key values you wish to get from each table.
  • Using one of the following ways, create an instance of the MultiTableBatchGet class: - Using one of the BatchGet objects you created in the previous step, call the Combine function. - A list of BatchGet objects is used to create an instance of the MultiBatchGet type. - Pass your list of BatchGet objects to the CreateMultiTableBatchGet function of DynamoDBContext.
  • Call MultiTableBatchGet's Execute function, which provides typed results in individual BatchGet objects.

The CreateBatchGet function is used in the following C# code to retrieve several items from the Employee and EmployeeWorkDetails databases.

Batch Write Items

This section will discuss Putting and deleting multiple items in a batch write operation. To put or delete in batch write, you need to consider the following.

  • First, execute the CreateBatchWrite method in the DynamoDB an create the BatchWrite class.
  • Mention the items you need to put or delete. For that:
    • If you put items, use the AddPutItem method or the AddPutItems method.
    • If you delete an item, You have to specify either the Item's primary key or the client-side object that maps to the Item you need to delete. Use the AddDeleteItem, AddDeleteItems, and the AddDeleteKey methods to specify the list of items to delete.
    • You can call BatchWrite.Execute, a method to put or delete specific items in the table.

Run Transactions

The following code snippet illustrates how to run the transactions in DynamoDB.

Run DynamoDB Local

.NET Core loads application configuration from a specified sequence of sources by default. In our situation, when the program begins in the development environment (the default when debugging from Visual Studio), the settings from this extra JSON file will supersede earlier configuration values. For example, the "LocalMode" has been set to true, and the service URL for the local DynamoDB instance is added.

We've selected the value to "http://localhost:8000", but you can change it if you want to run the container on a different host port.

The following code shows how to register the DynamoDB service.

We can manually register a service for the IAmazonDynamoDB interface if the LocalMode is true. We utilize the overload to offer an implementation factory that will return the actual implementation in this case. We use the LocalServiceUrl from configuration to build an AmazonDynamoDBConfig instance in our scenario. We then use that configuration to create and return the AmazonDynamoDBClient. We've set this up as a singleton, which means this code will only run once when the service is used.

If LocalMode is false, we need to utilize the AWS SDK helper method AddAWSService to add the service because we added the AWSSDK.Extensions.NETCore.Setup package.

If you want to see your local tables and data in them, you can use Dynobase to query and modify items in offline tables.

Learn more about running DynamoDB locally.

Dynobase is a Professional GUI Client for DynamoDB

First 7 days are on us. No strings attached.

Product Features

Download
/
Changelog
/
Pricing
/
Member Portal
/
Privacy
/
EULA
/
Twitter
© 2024 Dynobase