Step by step: .NET Core and Azure Cosmos DB

Step by step: .NET Core and Azure Cosmos DB is a short post on how to connect to Cosmos DB, save a document and then query to find it.

Let’s start:

1. Create a Cosmos DB account


Create a Cosmos DB account in your Azure subscription. Once created get the URI and the primary Read-write key from the Keys section.

If you need info on how to do this browse to the Create a database account section here: https://docs.microsoft.com/en-us/azure/cosmos-db/create-documentdb-dotnet

2. Create a folder for your new project


Open a command promt an run

1mkdir cosmosdb

3. Create the project


1cd cosmosdb
2dotnet new console

4. Add a reference to the Microsoft.Azure.DocumentDB.Core library


Add a reference to the Microsoft.Azure.DocumentDB.Core client library so you are able to talk with Cosmos Db.

1dotnet add package Microsoft.Azure.DocumentDB.Core -v 1.3.2

5. Restore packages


You just modified the project dependencies so please restore the packages with the following command:

1dotnet restore

6. Modify Program.cs


Replace the contents of the Program.cs file with the following code and remember to change lines 13 and 16 with your account URI and Key

 1using System;
 2using System.Linq;
 3using Microsoft.Azure.Documents;
 4using Microsoft.Azure.Documents.Client;
 5
 6namespace cosmosdb
 7{
 8    class Program
 9    {
10        static void Main(string[] args)
11        {
12            // The endpoint to your cosmosdb instance
13            var endpointUrl = "[THE ENPOINT OF YOUR COSMOSDB SERVICE HERE]";
14
15            // The key to you cosmosdb
16            var key = "[THE KEY OF YOUR COSMOSDB SERVICE HERE]";
17
18            // The name of the database
19            var databaseName = "Students";
20
21            // The name of the collection of json documents
22            var databaseCollection = "StudentsCollection";
23
24            // Create a cosmosdb client
25            using (var client = new DocumentClient(new Uri(endpointUrl), key))
26            {
27                // Create the database
28                client.CreateDatabaseIfNotExistsAsync(new Database() { Id = databaseName }).GetAwaiter().GetResult();
29
30                // Create the collection
31                client.CreateDocumentCollectionIfNotExistsAsync(
32                    UriFactory.CreateDatabaseUri(databaseName),
33                    new DocumentCollection { Id = databaseCollection }).
34                    GetAwaiter()
35                    .GetResult();
36
37                // Create a Student instance
38                var student = new Student() { Id = "Student.1", Name = "Carlos", LastName = "Mendible" };
39
40                // Sava the document to cosmosdb
41                client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseName, databaseCollection), student)
42                    .GetAwaiter().GetResult();
43
44                Console.WriteLine($"Student was saved in the database with id: {student.Id}");
45
46                // Query for the student by last name
47                var query = client.CreateDocumentQuery<Student>(
48                        UriFactory.CreateDocumentCollectionUri(databaseName, databaseCollection))
49                        .Where(f => f.LastName == "Mendible")
50                        .ToList();
51
52                if (query.Any())
53                {
54                    Console.WriteLine("Student was found in the cosmosdb database");
55                }
56
57            }
58        }
59    }
60
61    /// <summary>
62    /// A simple class representing a Student
63    /// </summary>
64    public class Student
65    {
66        public string Id { get; set; }
67
68        public string Name { get; set; }
69
70        public string LastName { get; set; }
71    }
72}

7. Build


Build the application with the following command

1dotnet build

8. Run


You are good to go so run the application

1dotnet run

You can get the code here: https://github.com/cmendible/dotnetcore.samples/tree/main/cosmosdb

Hope it helps!


Use PowerShell to Enable Logging for Azure RM Web Apps
Deploy your ASP.NET Core Web API to AWS Lambda
comments powered by Disqus