Azure NoSQL in ASP.NET Core 2.0

Problem

How to use Azure NoSQL database in ASP.NET Core.

Solution

Create a class library and add NuGet package: Microsoft.Azure.DocumentDB.Core

Add a class to encapsulate settings:

Add a class for repository, which will work with a generic type. Add a constructor and private methods to initialise the Azure client:

Add methods to get one or more items:

Now add public methods for the repository:

Inject and use repository:

In ASP.NET Core Web Application, configure services:

Discussion

The sample code will require you to setup Azure account, NoSQL database and collection. Instructions for these could be found at: https://docs.microsoft.com/en-gb/azure/cosmos-db/create-documentdb-dotnet#create-a-database-account

Source Code

GitHub: https://github.com/TahirNaushad/Fiver.Azure.NoSql

One comment

  1. Hi Tahir, in your experience, what is a best practice for setting the “id” of the document in DocumentDb? If the requestor on a POST (create) does not specify an ID in their input, should the service create one or should the service rely on DocumentDb to create it? In either case, the ID is necessary on the response message and if not supplied, errors out.

Leave a Reply