Disclaimer: I am a consultant at Amazon Web Services, and this is my personal blog. The opinions expressed here are solely mine and do not reflect the views of Amazon Web Services (AWS). Any statements made should not be considered official endorsements or statements by AWS.
In this post, we will understand how can we create a DynamoDB table in the AWS cloud and connect it with an ASP.NET Core application to perform CRUD operations.
We will be using the below tools and frameworks in this post going forward.
Login to your AWS account, and search for DynamoDB. On the DynamoDB page, select Tables > Create Table as shown in the below picture.
In this demo, we are creating a products
table with the following information.
In DynamoDB, we can have 2 types of primary keys.
Go to visual studio, create an ASP.NET Core project of your choice. Here, I will be creating an ASP.NET Core MVC application.
Provide some additional information such as your project name, project location, etc.
Here, I am using .NET 6 LTS version. Once you have provided all the information, just press the create button.
Now you have to install the following NuGet packages to use DynamoDB services in .NET.
AWSSDK.Extensions.NETCore.
Setup` to set up dependency injection for AWS Service Clients. AWSSDK.DynamoDBv2
to perform DynamoDB related operations.In this picture, you can see we have installed above mentioned NuGet packages.
Go to your appsettings.Development.json
file, and provide your local AWS credential profile information there in the below format.
Your appsettings.Development.json
file should look like the below:
Now, go to the Program.cs
file and add the below code. This will read AWS credential profile information from the configuration file and load it into AWS SDK.
Program.cs
file will look like this after adding the above code.
Check out my other blog Understanding Credential Loading in AWS SDK for .NET to understand how AWS SDK loads credentials in different environments.
Copy and paste the below lines in your Program.cs
to configure dependency injection.
Program.cs
file will look like this after adding above code.
Create an entity class to represent your DynamoDB table. Also, decorate this class with proper attributes.
Now, create an API Controller in your ASP.NET Core application and write the code to perform CRUD operations with the DynamoDB table.
Here is the code that I wrote for ProductController.cs file.
I tested these APIs using Visual Studio Code Rest Client extension. I have also copied the content of my api-testing.http
file below. You can use the same to test at your end.
Here is a screenshot that I took during the testing.
Now go to the AWS console, select table, and hit the scan button to view all the data.
That's all.
In this post, we learned how can we easily get started with DynamoDB using ASP.NET Core applications. Please let me know your thoughts and feedback in the comment section below.
Thank You ❤️