CRUD Operations In Azure Cosmos DB C#

CRUD Operations In Azure Cosmos DB C#

In this Azure tutorial, we will discuss CRUD Operations In Azure Cosmos DB C# or how to perform CRUD operations in Azure Cosmos DB. Along with this, we will also discuss the below topics.

CRUD Operations In Azure Cosmos DB C#

If you are very new to Azure Cosmos DB, then you are at the right place where you will learn the CRUD operations in Azure Cosmos DB using C#.

Well, before starting the CRUD operation in Azure Cosmos DB, let’s discuss the prerequisites that are needed here.

Prerequisites

Below are the prerequisites needed to perform the CRUD operation in Azure Cosmos DB.

Assuming you are ready with all the prerequisites needed here, let’s start with the actual functionality.

The first step is to create a console app using visual studio 2019.

Creating the Console Application

Follow the below steps to create the console app

  1. Open the Visual studio 2019 on your dev machine.
  2. Click on the Create a new Project button.
  3. Serach for the template “Console App (.Net Framework)” and Choose the template and click on the Next button.
  4. On the Configure your new project window, provide the below details
  • Project name: Provide a name for your project.
  • Location: Choose a location where you want to save your project.
  • Framework: Choose the latest .Net framework.

Finally, click on the Create button to create the console application.

How to perform CRUD Operations In Azure Cosmos DB

Now, the project has been created successfully. Now as the next step, we need to add the required NuGet package to the solution.

Adding the Nuget package

  • To add the Nuget package, Right-click on the project –> Select the Manage NuGet Packages option.
How to perform CRUD operations in Azure Cosmos DB using C#
  • Under the Browse tab, search for ‘documentdb’.
  • Click on the search result Microsoft.Azure.DocumentDB and click on the Install button as highlighted below.
CRUD Operations In Azure Cosmos DB
  • Now. click on the I Accept button to start the installation. it will take a few seconds to finish the installation.

As the next step, let’s do the App.config file changes. Add the below code in the App.config file

<appSettings>  
  <!--This is your Azure Cosmos DB Endpoint URL-->  
  <add key="Endpoint" value =""/>  
<!--This is your Azure Cosmos DB Primary Key-->  
  <add key="PrimaryKey" value =""/>  
</appSettings>

Now, to get the values of the Endpoint and the Primary key of the Azure Cosmos DB, you need to follow the below instructions.

  • Login to the Azure Portal and navigate to your Azure Cosmos DB account.
  • On the Azure Cosmos DB account page, click on the Keys option from the left navigation.
  • Copy the URI value which is nothing but the value for the Endpoint key that we have mentioned on the App.config file.
  • Now, Copy the Primarykey value which is nothing but the value for the Primarykey that we have mentioned on the App.config file.
CRUD Operations In Cosmos DB

The complete App.config file will be like below

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.4.1" newVersion="4.0.4.1" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <appSettings>
    <!--This is your Azure Cosmos DB Endpoint URL-->
    <add key="Endpoint" value ="https://mydemocdb38.documents.azure.com:xxx/"/>
    <!--This is your Azure Cosmos DB Primary Key-->
    <add key="PrimaryKey" value ="YM5doVlb8lnNt6Qfc7zAdNxxxxxxxxxxxxxxxxxxxxxxxxNMmA623ot6csj71RwrVuh0YHhuHCo5eWq3DekhNiw=="/>
  </appSettings>
</configuration>

Note: Make sure to update the value for the Endpoint URI and Primary key based on yours.

Now, we need to do the code changes for the Program.cs file. The first step is, we need to initialize the document client instance. For that, we need to add the below references and using statements.

Add the reference of System.Configuration to your project, For adding the reference, Right-click on the project –> Add –> Reference.

Search for System.Configuration and then select System.Configuration and click on the Ok button.

CRUD Operations Azure Cosmos DB

Once, you have added the reference, add the below-using statement in the Program.cs file.

using System.Configuration;

Along with that, you need to add the below-using statement.

using Microsoft.Azure.Documents.Client;

Initializing the document client instance

Now, the complete code to initialize the document client instance is as below

using Microsoft.Azure.Documents.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Threading.Tasks;

namespace CRUDCosmosDB
{
    class Program
    {
        static void Main(string[] args)
        {
            Task.Run(async () =>
            {
                var ep = ConfigurationManager.AppSettings["Endpoint"];
                var pk = ConfigurationManager.AppSettings["PrimaryKey"];
                using (var client = new DocumentClient(new Uri(ep), pk))
                {

                }

            }).Wait();
        }
    }
}

If you will not add the reference for the System.Configuration, you will get the error as below

The name ‘ConfigurationManager’ does not exist in the current context

To fix this error make sure to add the reference of System. Configuration as explained above.

Creating Azure Cosmos DB database

Now as the next step we need to create the Azure Cosmos DB database. You need to add the below lines of code for creating the Azure Cosmos DB database.

Before that make sure to add the below-using statement.

using Microsoft.Azure.Documents;

Below is the code to create the Azure Cosmos DB database.

Console.WriteLine("\r\n Creating your Azure Cosmos Database..........");
                    //TSINFODB is the name of my database
                    var df = new Database { Id = "TSINFODB" };
                    var db = await client.CreateDatabaseIfNotExistsAsync(df);
                    Console.WriteLine("Database TSINFODB created successfully");

The Program.cs file as of now is as below.

using Microsoft.Azure.Documents.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;

namespace CRUDCosmosDB
{
    class Program
    {
        static void Main(string[] args)
        {
            Task.Run(async () =>
            {
                var ep = ConfigurationManager.AppSettings["Endpoint"];
                var pk = ConfigurationManager.AppSettings["PrimaryKey"];
                using (var client = new DocumentClient(new Uri(ep), pk))
                {
                    Console.WriteLine("\r\n Creating your Azure Cosmos Database..........");
                    //TSINFODB is the name of my database
                    var df = new Database { Id = "TSINFODB" };
                    var db = await client.CreateDatabaseIfNotExistsAsync(df);
                    Console.WriteLine("Database TSINFODB created successfully");
                }

            }).Wait();
        }
    }
}

Creating the Azure Cosmos DB collection

As the next step, we need to create the Azure Cosmos DB collection. You can use the below code for the same.

//TSINFODBCollection is the name of the Azure Cosmos Database Collection
              
                    Console.WriteLine("\r\nCreating your Azure Cosmos Database Collection......");
                    var cd = new DocumentCollection { Id = "TSINFODBCollection" };
                    var collection = await client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("TSINFODB"),
                        cd);
                    Console.WriteLine("Collection TSINFODBCollection created successfully");

Till now, the code is as below

using Microsoft.Azure.Documents.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;

namespace CRUDCosmosDB
{
    class Program
    {
        static void Main(string[] args)
        {
            Task.Run(async () =>
            {
                var ep = ConfigurationManager.AppSettings["Endpoint"];
                var pk = ConfigurationManager.AppSettings["PrimaryKey"];
                using (var client = new DocumentClient(new Uri(ep), pk))
                {
                    Console.WriteLine("\r\n Creating your Azure Cosmos Database..........");
                    //TSINFODB is the name of my database
                    var df = new Database { Id = "TSINFODB" };
                    var db = await client.CreateDatabaseIfNotExistsAsync(df);
                    Console.WriteLine("Database TSINFODB created successfully");
                   //TSINFODBCollection is the name of the Azure Cosmos Database Collection
              
                    Console.WriteLine("\r\nCreating your Azure Cosmos Database Collection......");
                    var cd = new DocumentCollection { Id = "TSINFODBCollection" };
                    var collection = await client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("TSINFODB"),
                        cd);
                    Console.WriteLine("Collection TSINFODBCollection created successfully");
                }

            }).Wait();
        }
    }
}

Insert Operation: Inserting a document to the Collection

Now, let’s try to perform the insert operation where we will insert a document to the database collection that we have created above. You can use the below code for the same

//Inserting a new Document to the database collection 
                    Console.WriteLine("\r\n Inserting document to the Database Collection......");
                    dynamic def = new
                    {
                        title = "Samsumng ",
                        review = 40,
                        category = "Monitor"
                    };
                    var document1 = await client.CreateDocumentAsync(
                        UriFactory.CreateDocumentCollectionUri("TSINFODB", "TSINFODBCollection"),
                        def);

The code as of now is as below

using Microsoft.Azure.Documents.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;

namespace CRUDCosmosDB
{
    class Program
    {
        static void Main(string[] args)
        {
            Task.Run(async () =>
            {
                var ep = ConfigurationManager.AppSettings["Endpoint"];
                var pk = ConfigurationManager.AppSettings["PrimaryKey"];
                using (var client = new DocumentClient(new Uri(ep), pk))
                {
                    Console.WriteLine("\r\n Creating your Azure Cosmos Database..........");
                    //TSINFODB is the name of my database
                    var df = new Database { Id = "TSINFODB" };
                    var db = await client.CreateDatabaseIfNotExistsAsync(df);
                    Console.WriteLine("Database TSINFODB created successfully");
                    //TSINFODBCollection is the name of the Azure Cosmos Database Collection
              
                    Console.WriteLine("\r\nCreating your Azure Cosmos Database Collection......");
                    var cd = new DocumentCollection { Id = "TSINFODBCollection" };
                    var collection = await client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("TSINFODB"),
                        cd);
                    Console.WriteLine("Collection TSINFODBCollection created successfully");

                    //Inserting a new Document to the database collection 
                    Console.WriteLine("\r\n Inserting document to the Database Collection......");
                    dynamic def = new
                    {
                        title = "Samsumng ",
                        review = 40,
                        category = "Monitor"
                    };
                    var document1 = await client.CreateDocumentAsync(
                        UriFactory.CreateDocumentCollectionUri("TSINFODB", "TSINFODBCollection"),
                        def);
                }

            }).Wait();
        }
    }
}

Now let’s query the database using the below lines of code

Console.WriteLine("\r\n Started Querying the document from the database............");
                    var rsp = client.CreateDocumentQuery
                    (UriFactory.CreateDocumentCollectionUri("TSINFODB", "TSINFODBCollection"),
                        "select * from c").ToList();
                    var doc = rsp.First();
                    Console.WriteLine($"Id:{doc.id}");
                    Console.WriteLine($"Title:{doc.title}");
                    Console.WriteLine($"review:{doc.review}");
                    Console.WriteLine($"category:{doc.category}");

Delete Operation: Deleting the database collection

Finally, the delete operation uses the below code to delete the database collection.

//Deleting the database collection
                    Console.WriteLine("\r\n Deleteing the database Collection ................");
                    await client.DeleteDocumentCollectionAsync(
                    UriFactory.CreateDocumentCollectionUri("TSINFODB", "TSINFODBCollection"));

Finally, the complete code for the CRUD operation on the Azure Cosmos DB is here.

using Microsoft.Azure.Documents.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;

namespace CRUDCosmosDB
{
    class Program
    {
        static void Main(string[] args)
        {
            Task.Run(async () =>
            {
                var ep = ConfigurationManager.AppSettings["Endpoint"];
                var pk = ConfigurationManager.AppSettings["PrimaryKey"];
                using (var client = new DocumentClient(new Uri(ep), pk))
                {
                    Console.WriteLine("\r\n Creating your Azure Cosmos Database..........");
                    //TSINFODB is the name of my database
                    var df = new Database { Id = "TSINFODB" };
                    var db = await client.CreateDatabaseIfNotExistsAsync(df);
                    Console.WriteLine("Database TSINFODB created successfully");
                    //TSINFODBCollection is the name of the Azure Cosmos Database Collection
              
                    Console.WriteLine("\r\nCreating your Azure Cosmos Database Collection......");
                    var cd = new DocumentCollection { Id = "TSINFODBCollection" };
                    var collection = await client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("TSINFODB"),
                        cd);
                    Console.WriteLine("Collection TSINFODBCollection created successfully");

                    //Inserting a new Document to the database collection 
                    Console.WriteLine("\r\n Inserting document to the Database Collection......");
                    dynamic def = new
                    {
                        title = "Samsumng ",
                        review = 40,
                        category = "Monitor"
                    };
                    var document1 = await client.CreateDocumentAsync(
                        UriFactory.CreateDocumentCollectionUri("TSINFODB", "TSINFODBCollection"),
                        def);
                    //Querying the document from the database
                    Console.WriteLine("\r\n Started Querying the document from the database............");
                    var rsp = client.CreateDocumentQuery
                    (UriFactory.CreateDocumentCollectionUri("TSINFODB", "TSINFODBCollection"),
                        "select * from c").ToList();
                    var doc = rsp.First();
                    Console.WriteLine($"Id:{doc.id}");
                    Console.WriteLine($"Title:{doc.title}");
                    Console.WriteLine($"review:{doc.review}");
                    Console.WriteLine($"category:{doc.category}");
                    ////Deleting the database collection
                    //Console.WriteLine("\r\n Deleteing the database Collection ................");
                    //await client.DeleteDocumentCollectionAsync(
                    //UriFactory.CreateDocumentCollectionUri("TSINFODB", "TSINFODBCollection"));
                }

            }).Wait();
        }
    }
}

For the time being, I have commented on the code to delete the database collection and ran the console application.

How to do CRUD Operations In Azure Cosmos DB

To cross-check, it is working as expected, I have logged in to the Azure Portal and went to the Azure Cosmos DB account and can able to see the expected output.

CRUD Operations In Azure Cosmos DB using C#

Now, I have uncommented the code to delete the database container, I can able to see that the database collection has been deleted successfully.

cosmos db c# example

You may also like following the below articles

Wrapping Up

Well, in this article, we have discussed CRUD Operations In Azure Cosmos DB C#, How to perform CRUD operations in Azure Cosmos DB C#.

Hope it will help you !!!