Cosmos DB CRUD Operations C#

CRUD Operations In Azure Cosmos DB C#

This Azure tutorial 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#.

Before starting the CRUD operation in Azure Cosmos DB, let’s discuss the prerequisites needed here.

Prerequisites

Below are the prerequisites to perform the Azure Cosmos DB’s CRUD operation.

Let’s start with the actual functionality if you are ready with all the prerequisites.

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. Search for the template “Console App (.Net Framework).” 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.

cosmos db crud operations c#

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

Adding the NuGet package

  • To add the Nuget package, Right-click on the project and select the Manage NuGet Packages option.
azure cosmos db crud c#
  • Under the Browse tab, search for ‘documentdb’.
  • Click on the search result in Microsoft.Azure.DocumentDB and click on the Install button, as highlighted below.
cosmos db crud operations
  • 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 code below to 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>

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

  • Log in to the Azure Portal and navigate to your Azure Cosmos DB account.
  • On the Azure Cosmos DB account page, click 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.
  • Copy the Primarykey value, which is nothing but the value for the Primarykey we have mentioned on the App. config file.
crud operations in cosmos db c#

The complete App. config file will be like the 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 make 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.

cosmos db c# example

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

As the next step, we must 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 follows.

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 must 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 into 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 now, I have commented on the code to delete the database collection and run the console application.

cosmos db c#

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 see the expected output.

azure cosmos db tutorial c#

Now, that 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 articles below

Wrapping Up

In this article, we have discussed CRUD Operations In Azure Cosmos DB C# and how to perform CRUD operations in Azure Cosmos DB C#. I hope it will help you !!!