Inserting Data into Cosmos DB Using ASP.NET Core API

In this article, we will learn how to insert the data into the Azure Cosmos DB with SQL API using the ASP.NET Core API. Let's learn step by step.

Step 1: Set up Prerequisites

To perfrom the insert  operation in the Azure Cosmos DB we are required the following one the of the Prerequisites.

  • Azure Subscription OR
  • Azure Cosmos DB Emulator 

Azure Subscription 

To create the Azure cloud Cosmos DB account, you need an active Azure subscription. When you create the Cosmos DB account on the cloud, the Azure Cosmos DB Serverless account provides the first 1000 RU and 25 GB of storage for free per subscription.

Refer to the following link to learn the basics and how to create the Azure Cosmos DB account.

Azure Cosmos DB Emulator (offline)

As explained, the first approach requires an active Azure subscription as well as an active internet connection, which is not feasible for everyone who just wants to explore or learn about the Azure Cosmos DB.

To overcome the preceding issue, we can use the Azure Cosmos DB capabilities and features using the Azure Cosmos DB Emulator without an active Azure subscription or an active internet connection.

The Azure Cosmos DB Emulator currently does not have support for all the NoSQL API's, but it will support the most commonly used NoSQL API's such as the SQL API and Mongo DB API, and in the future it may also support all the Cosmos DB API's.

The following is the link to download the Azure Cosmos DB Emulator.

After clicking on the link, the official Microsoft documentation website gets opened, from which you can find and install the latest version of the Azure Cosmos DB Emulator.

Step 2: Create Azure Cosmos DB 

In this article, we are going to use the Azure Cosmos DB emulator instead of a Cloud Azure Cosmos DB account. If you are a beginner, then please refer to the following articles to learn how to create an Azure Cosmos DB account.
We are using the Azure Cosmos DB emulator in this article. search for the Azure Cosmos DB emulator from the search bar of the window once you download and install the emulator, which looks like the following:



The preceding image shows the Azure CosmosDB Account of the emulator, which will provide the same features as the Cloud Azure CosmosDB Account for development. Now click on the explorer and create the database and container. The explorer will then look like this:



We are storing the employee basic data in the Azure CosmosDB, and we are planning to use Department as a partition key and ID as the unique id for our employee records.

Note:
  • The ID and Department properties should be part of your backend input while inserting or updating the records; otherwise, you will get the exceptions.
I hope you have completed the required setup as explained in this article, including the creation of the Azure Cosmos account and database.

Step 3: Create ASP.NET Core web api Project

  1. Start then  All Programs and select "Microsoft Visual Studio".
  2. Once the Visual Studio Opens, Then click on Continue Without Code.
  3. Then Go to Visual Studio Menu, click on File => New Project then choose ASP.NET Core Web Api Project Template.
  4. Then define the project name, location of the project, then click on the next button.
  5. On the next screen, provide the additional details: framework, authentication type, and check the Enable Open API Support checkbox as shown below.


The preceding steps will create the ASP.NET Core Web API application and solution explorer. It will look like what is shown in the following image.



Step 4: Add Microsoft.Azure.Cosmos Nuget Package Reference

The Microsoft.Azure.Cosmos is the the latest nuget package to interact with the Azure cosmos DB. The Microsoft.Azure.Cosmos supports the basic to custom and complex database operations, follow the following steps to add the Nuget package.

  1. Right click on the Solution Explorer, find Manage NuGet Package Manager and click on it
  2. After as shown into the image and type in search box Microsoft.Azure.Cosmos
  3. Select Microsoft.Azure.Cosmos as shown into the image, 
  4. Choose version of Microsoft.Azure.Cosmos library and click on install button


I hope you have followed the same steps and installed the Microsoft.Azure.Cosmos nuget package.The next step is to delete the default controller and model class so we can start from scratch.


Step 5:Create the Model Class

  • First, delete the default model class, which is created outside the folder structure, so we can start from scratch. 
  • Next, create the folder named Model by right clicking on the solution explorer.
  • Create the model class Employee Model by right clicking on the Model folder, as shown in the following image


Now open the EmployeeModel.cs class file and add the following code.

EmployeeModel.cs

namespace EmployeeManagement.Model
{
    public class EmployeeModel
    {
        public string? id { get; set; }
        public string? Name { get; set; }
        public string? Country { get; set; }
        public string? City { get; set; }       
        public string? Department { get; set; }
        public string? Designation { get; set; }
        public DateTime? JoiningDate { get; set; }

    }
}

Step 6: Add the Controller

Create the Empty API Controller class EmployeeController by right clicking on the Controller folder as shown in the following image.



After adding the model class and API controller class, the solution explorer will look like the following:




Now open the EmployeeController.cs file and add the add the following configuration.
  • Define the following route at controller level, so that we can add the multiple Get, Post, Put, or Delete and avoid the name ambiguity exception.
    [ApiController]
    [Route("[api/[controller]/[action]]")]
    public class EmployeeController : ControllerBase
    {
    }

  • Declare the following variable and set the Azure Cosmos DB configuration by copying the details from step 2.
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class EmployeeController : ControllerBase
    {
       
        // Cosmos DB details, In real use cases, these details should be configured in secure configuraion file.
        private readonly string CosmosDBAccountUri = "https://localhost:8081/";
        private readonly string CosmosDBAccountPrimaryKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
        private readonly string CosmosDbName = "EmployeeManagementDB";
        private readonly string CosmosDbContainerName = "Employees";
}

Step 7: Create Method to Add Employee

Add the following code into the EmployeeController.cs class to Add the employees into the CosmosDB. This method takes input values using  the EmployeeModel class. 

        [HttpPost]
        public async Task<IActionResult> AddEmployee(EmployeeModel employee)
        {
            try
            {
                var container = ContainerClient();
                var response = await container.CreateItemAsync(employee, new PartitionKey(employee.Department));

                return Ok(response);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }
               
        } 



As explained in step 2, we are passing the ID and Department as a partition key as part of the employee input payload while adding the employee details. These parameters must be part of the input parameter payload.

The entire code of the EmployeeController.cs class file will look like the following after adding all the methods together:

EmployeeController.cs

using EmployeeManagement.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Cosmos;

namespace EmployeeManagement.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class EmployeeController : ControllerBase
    {
       
        // Cosmos DB details, In real use cases, these details should be configured in secure configuraion file.
        private readonly string CosmosDBAccountUri = "https://localhost:8081/";
        private readonly string CosmosDBAccountPrimaryKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
        private readonly string CosmosDbName = "EmployeeManagementDB";
        private readonly string CosmosDbContainerName = "Employees";


        /// <summary>
        /// Commom Container Client, you can also pass the configuration paramter dynamically.
        /// </summary>
        /// <returns> Container Client </returns>
        private  Container  ContainerClient()
        {

            CosmosClient cosmosDbClient = new CosmosClient(CosmosDBAccountUri, CosmosDBAccountPrimaryKey);
            Container containerClient = cosmosDbClient.GetContainer(CosmosDbName, CosmosDbContainerName);
            return containerClient;
           
        }


        [HttpPost]
        public async Task<IActionResult> AddEmployee(EmployeeModel employee)
        {
            try
            {
                var container = ContainerClient();
                var response = await container.CreateItemAsync(employee, new PartitionKey(employee.Department));

                return Ok(response);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }
               
        }

    }
}

Now, we have all the code and required configuration to work with Azure CosmosDB in our sample application.

Step 8: Run the ASP.NET Core API Application

Now press Keyboard F5 or the Visual Studio Run button to run the application. After running the application, the following screen will be shown in the browser with swagger UI having all the methods which we have created in our ASP.NET core web API, as shown in the following screenshot:




Now, we will test the functionality by using the Swagger UI, but you can use Postman or any other tool to execute the API endpoints.

Step 9: Azure Cosmos DB Data Insert Demo 

The following animated image shows how the data gets added to the Azure Cosmos DB with SQL API.

Add Employees


Summary

Cosmos DB Free Tier Limitations

In this article, I will explain how to use the Azure Cosmos DB free tier and the limitations of the Azure Cosmos DB free tier plan. The Azure Cosmos DB free tier enables a developer or learner to quickly get started, test or learn about the Azure Cosmos DB, and even deploy test applications.

The free tier discount can be used in the following two ways:

  • Azure Cosmos DB Free Tier (paid or corporate subscription)
  • Azure Free Account (Free Azure Account for Learners )

The Azure Cosmos DB Free Tier and the Azure Free Account are two different things. The Azure Cosmos DB Free Tier is typically associated with corporate or paid subscriptions, whereas the Azure Free Account is a Microsoft offering that allows users to learn about Azure Services by creating a free account for a limited time or for the duration of the subscription.

The Cosmos DB free tier discount can be applied during the creation of the Cosmos DB account. During account creation, the following options will be available, as shown in the following image:


Azure Cosmos DB Free Tier Limitations and Features

  • The Azure Cosmos DB free tier discount is only supported in provisioned throughput capacity mode.
  • This free discount is not yet supported in the serverless capacity mode.
  • The discount can be applied to only one Cosmos DB account per subscription, meaning you cannot apply the discount to two Cosmos DB accounts in the same subscription.
  • The dedicated throughput is not supprted since the throughput is shared across all the containers in the database.
  • The maximum of 1000 RU per second is supported on the database level, which can be shared across containers.
  • The maximum of 25 GB of storage is free per account, along with the first 1000 RU/s.
  • The maximum of 25 containers created per database is similar to the normal account, but the limit for the free discount is that the throughput is shared across all the containers.
  • Beyond 1000 RU/s and the maximum storage capacity, the normal charges are applied.
  • If you create a free Azure account, you will receive combined benefits for the first 12 months, which means you will receive 400 RU/s of free Azure account and 1000 RU/s for Azure Cosmos DB free tier disccount, totaling 1400 RU/s for the first 12 months, after which the regular Azure free account limits will apply.
  • The same combined benefits are applied for the storage. You will get the 25 GB of Azure free account and the 25 GB of Cosmos DB free tier discount, which combined are 50 GB for 12 months. After the 12 months, the normal limits are applied for the lifetime of your free Azure account.

I hope, from all the examples above, you have learned how to use the Azure Cosmos DB free tier and the limitations of the Azure Cosmos DB free tier plan. I. If you like it, share it with your friends and subscribe to the blog and YouTube channel for more articles.

Swagger Failed to load API definition In ASP.NET Core API

In this article, we will learn how to resolve the ASP.NET Core API Swagger Failed to load API Definition issue.

You can refer to the following link for the related articles: 

What is the root cause of the API definition loading issue?

The default API controller route configuration is the cause of this issue. When we add the API controller in the ASP.NET Core API application, by default it has controller-specific routes, which means it can support only a single method for each of the HTTP verbs Post, PUT, Delete, GET, and Patch.

There may be a requirement when we need to create more than one method having the Http verbs Post, PUT, Delete, GET, and Patch in a single API controller, and if you create the method with the default route configuration in the API controller class without modifying the default route configuration, then you will get the exception "Failed to load API definition" while loading the swagger UI in the ASP.NET Core web API.

What is the Solution?

The solution is that you have to change the default route configuration at the controller level when you have created more than one method with the HTTP verbs "post," "put," and "get." Delete or Put in the single API controller class.

Consider the following example: I have created the ASP.NET Core API application, which has by default one Get method, GetWeatherForecast, which returns the WeatherForecast. Then I have added one more Get method named WeatherForecastByCity in the default API Controller class without modifying the default route.

 [ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }

    [HttpGet(Name = "WeatherForecastByCity")]
    public IEnumerable<WeatherForecast> Get(string city)
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

When we have run the application, we will get the Swagger loading error,


Now change the default route at controller level which can support more than one method having the Http verbs Post, PUT, Delete, GET, and Patch in a single controller.

[Route("api/[controller]/[action])]

Also, remove the name of the method from the HTTP verb, which is defined using the Name attribute; just define the HTTP verb and proper method name.


Change from

   [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }


To 
 
   [HttpGet]
    public IEnumerable<WeatherForecast> GetWeatherForecast()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }

Full Code







d[ApiController] [Route("api/[controller]/[action]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> GetWeatherForecast() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } [HttpGet] public IEnumerable<WeatherForecast> WeatherForecastByCity(string city) { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } }

Now, run the application again after changing the default route, and you will see swagger loads without any issue.


Summary

I hope this article helps you fix the issue. "Swagger failed to load API definitions in the ASP.NET Core API." If you have any questions, then send them using the comment box.

Related Articles

CRUD Operations In Azure Cosmos DB Using ASP.NET Core Web API

In this article, we will learn how to insert, read, update, and delete records in the Azure Cosmos DB SQL API using the ASP.NET Core Web API. Let's learn step by step.

Step 1: Set up Prerequisites

To perfrom the CRUD operation in the Azure Cosmos DB we are required the following one the of the Prerequisites.

  • Azure Subscription OR
  • Azure Cosmos DB Emulator 

Azure Subscription 

To create the Azure cloud Cosmos DB account, you need an active Azure subscription. When you create the Cosmos DB account on the cloud, the Azure Cosmos DB Serverless account provides the first 1000 RU and 25 GB of storage for free per subscription.

Refer to the following link to learn the basics and how to create the Azure Cosmos DB account.

Azure Cosmos DB Emulator (offline)

As explained, the first approach requires an active Azure subscription as well as an active internet connection, which is not feasible for everyone who just wants to explore or learn about the Azure Cosmos DB.

To overcome the preceding issue, we can use the Azure Cosmos DB capabilities and features using the Azure Cosmos DB Emulator without an active Azure subscription or an active internet connection.

The Azure Cosmos DB Emulator currently does not have support for all the NoSQL API's, but it will support the most commonly used NoSQL API's such as the SQL API and Mongo DB API, and in the future it may also support all the Cosmos DB API's.

The following is the link to download the Azure Cosmos DB Emulator.

After clicking on the link, the official Microsoft documentation website gets opened, from which you can find and install the latest version of the Azure Cosmos DB Emulator.

Step 2: Create Azure Cosmos DB 

In this article, we are going to use the Azure Cosmos DB emulator instead of a Cloud Azure Cosmos DB account. If you are a beginner, then please refer to the following articles to learn how to create an Azure Cosmos DB account.
We are using the Azure Cosmos DB emulator in this article. search for the Azure Cosmos DB emulator from the search bar of the window once you download and install the emulator, which looks like the following:



The preceding image shows the Azure CosmosDB Account of the emulator, which will provide the same features as the Cloud Azure CosmosDB Account for development. Now click on the explorer and create the database and container. The explorer will then look like this:



We are storing the employee basic data in the Azure CosmosDB, and we are planning to use Department as a partition key and ID as the unique id for our employee records.

Note:
  • The ID and Department properties should be part of your backend input while inserting or updating the records; otherwise, you will get the exceptions.
I hope you have completed the required setup as explained in this article, including the creation of the Azure Cosmos account and database.

Step 3: Create ASP.NET Core web api Project

  1. Start then  All Programs and select "Microsoft Visual Studio".
  2. Once the Visual Studio Opens, Then click on Continue Without Code.
  3. Then Go to Visual Studio Menu, click on File => New Project then choose ASP.NET Core Web Api Project Template.
  4. Then define the project name, location of the project, then click on the next button.
  5. On the next screen, provide the additional details: framework, authentication type, and check the Enable Open API Support checkbox as shown below.


The preceding steps will create the ASP.NET Core Web API application and solution explorer. It will look like what is shown in the following image.



Step 4: Add Microsoft.Azure.Cosmos Nuget Package Reference

The Microsoft.Azure.Cosmos is the the latest nuget package to interact with the Azure cosmos DB. The Microsoft.Azure.Cosmos supports the basic to custom and complex database operations, follow the following steps to add the Nuget package.

  1. Right click on the Solution Explorer, find Manage NuGet Package Manager and click on it
  2. After as shown into the image and type in search box Microsoft.Azure.Cosmos
  3. Select Microsoft.Azure.Cosmos as shown into the image, 
  4. Choose version of Microsoft.Azure.Cosmos library and click on install button


I hope you have followed the same steps and installed the Microsoft.Azure.Cosmos nuget package.The next step is to delete the default controller and model class so we can start from scratch.


Step 5:Create the Model Class

  • First, delete the default model class, which is created outside the folder structure, so we can start from scratch. 
  • Next, create the folder named Model by right clicking on the solution explorer.
  • Create the model class Employee Model by right clicking on the Model folder, as shown in the following image


Now open the EmployeeModel.cs class file and add the following code.

EmployeeModel.cs

namespace EmployeeManagement.Model
{
    public class EmployeeModel
    {
        public string? id { get; set; }
        public string? Name { get; set; }
        public string? Country { get; set; }
        public string? City { get; set; }       
        public string? Department { get; set; }
        public string? Designation { get; set; }
        public DateTime? JoiningDate { get; set; }

    }
}

Step 6: Add the Controller

Create the Empty API Controller class EmployeeController by right clicking on the Controller folder as shown in the following image.



After adding the model class and API controller class, the solution explorer will look like the following:




Now open the EmployeeController.cs file and add the add the following configuration.
  • Define the following route at controller level, so that we can add the multiple Get, Post, Put, or Delete and avoid the name ambiguity exception.
    [ApiController]
    [Route("[api/[controller]/[action]]")]
    public class EmployeeController : ControllerBase
    {
    }

  • Declare the following variable and set the Azure Cosmos DB configuration by copying the details from step 2.
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class EmployeeController : ControllerBase
    {
       
        // Cosmos DB details, In real use cases, these details should be configured in secure configuraion file.
        private readonly string CosmosDBAccountUri = "https://localhost:8081/";
        private readonly string CosmosDBAccountPrimaryKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
        private readonly string CosmosDbName = "EmployeeManagementDB";
        private readonly string CosmosDbContainerName = "Employees";
}

Step 7: Create Method to Add Employee

Add the following code into the EmployeeController.cs class to Add the employees into the CosmosDB. This method takes input values using  the EmployeeModel class. 

        [HttpPost]
        public async Task<IActionResult> AddEmployee(EmployeeModel employee)
        {
            try
            {
                var container = ContainerClient();
                var response = await container.CreateItemAsync(employee, new PartitionKey(employee.Department));

                return Ok(response);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }
               
        }


As explained in step 2, we are passing the ID and Department as a partition key as part of the employee input payload while adding the employee details. These parameters must be part of the input parameter payload.

Step 8:  Create Method to Get Employees

Add the following code into the EmployeeController.cs class to get all the employees from the Cosmos database.

        [HttpGet]
        public async Task<IActionResult> GetEmployeeDetails()
        {
            try
            {
                var container = ContainerClient();
                var sqlQuery = "SELECT * FROM c";
                QueryDefinition queryDefinition = new QueryDefinition(sqlQuery);
                FeedIterator<EmployeeModel> queryResultSetIterator = container.GetItemQueryIterator<EmployeeModel>(queryDefinition);


                List<EmployeeModel> employees = new List<EmployeeModel>();

                while (queryResultSetIterator.HasMoreResults)
                {
                    FeedResponse<EmployeeModel> currentResultSet = await queryResultSetIterator.ReadNextAsync();
                    foreach (EmployeeModel employee in currentResultSet)
                    {
                        employees.Add(employee);
                    }
                }

                return Ok(employees);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }
           
        }


This example is not good practise since we are fetching all the employees without paging or a partition key filter, but we are doing this to learn how it works without making it complicated. In the next article, I will show how to get a list of records with the paging.

Step 9: Create Method to Get Employee by ID

Create the GetEmployeeDetailsById method in the EmployeeController.cs and add the following code to get the employee by employeeId and partition key from the Cosmos database.


        [HttpGet]
        public async Task<IActionResult> GetEmployeeDetailsById(string employeeId,string partitionKey)
        {

            try
            {
                var container = ContainerClient();
                ItemResponse<EmployeeModel> response = await container.ReadItemAsync<EmployeeModel>(employeeId, new PartitionKey(partitionKey));
                return Ok(response.Resource);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }

        }

Step 10: Create Method to Update Employee

Create the UpdateEmployee method in the EmployeeController.cs and add the following code to update  the employee by employeeId and partition key.

The CosmosDB does not support the partial update feature; rather, it actually replaces the existing item by getting the document to be updated and sending the same details to the database after fields to change or update.

       [HttpPut]
        public async Task<IActionResult> UpdateEmployee(EmployeeModel emp,string partitionKey)
        {

            try
            {

                var container = ContainerClient();
                ItemResponse<EmployeeModel> res = await container.ReadItemAsync<EmployeeModel>(emp.id, new PartitionKey(partitionKey));

                //Get Existing Item
                var existingItem = res.Resource;

                //Replace existing item values with new values 
                existingItem.Name = emp.Name;
                existingItem.Country = emp.Country;
                existingItem.City = emp.City;
                existingItem.Department = emp.Department;
                existingItem.Designation = emp.Designation;

              var updateRes=  await container.ReplaceItemAsync(existingItem, emp.id, new PartitionKey(partitionKey));

                return Ok(updateRes.Resource);

            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }
          
        }

Step 11: Create Method to Delete Employee

Create the DeleteEmployee method in the EmployeeController.cs and add the following code to delete the employee by employeeId and partition key.

        [HttpDelete]
        public async Task<IActionResult> DeleteEmployee(string empId, string partitionKey)
        {

            try
            {

                var container = ContainerClient();
               var response= await container.DeleteItemAsync<EmployeeModel>(empId, new PartitionKey(partitionKey));
                return Ok(response.StatusCode);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }
        }

    }

The entire code of the EmployeeController.cs class file will look like the following after adding all the methods together:

EmployeeController.cs

using EmployeeManagement.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Cosmos;

namespace EmployeeManagement.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class EmployeeController : ControllerBase
    {
       
        // Cosmos DB details, In real use cases, these details should be configured in secure configuraion file.
        private readonly string CosmosDBAccountUri = "https://localhost:8081/";
        private readonly string CosmosDBAccountPrimaryKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
        private readonly string CosmosDbName = "EmployeeManagementDB";
        private readonly string CosmosDbContainerName = "Employees";


        /// <summary>
        /// Commom Container Client, you can also pass the configuration paramter dynamically.
        /// </summary>
        /// <returns> Container Client </returns>
        private  Container  ContainerClient()
        {

            CosmosClient cosmosDbClient = new CosmosClient(CosmosDBAccountUri, CosmosDBAccountPrimaryKey);
            Container containerClient = cosmosDbClient.GetContainer(CosmosDbName, CosmosDbContainerName);
            return containerClient;
           
        }


        [HttpPost]
        public async Task<IActionResult> AddEmployee(EmployeeModel employee)
        {
            try
            {
                var container = ContainerClient();
                var response = await container.CreateItemAsync(employee, new PartitionKey(employee.Department));

                return Ok(response);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }
               
        }

        [HttpGet]
        public async Task<IActionResult> GetEmployeeDetails()
        {
            try
            {
                var container = ContainerClient();
                var sqlQuery = "SELECT * FROM c";
                QueryDefinition queryDefinition = new QueryDefinition(sqlQuery);
                FeedIterator<EmployeeModel> queryResultSetIterator = container.GetItemQueryIterator<EmployeeModel>(queryDefinition);


                List<EmployeeModel> employees = new List<EmployeeModel>();

                while (queryResultSetIterator.HasMoreResults)
                {
                    FeedResponse<EmployeeModel> currentResultSet = await queryResultSetIterator.ReadNextAsync();
                    foreach (EmployeeModel employee in currentResultSet)
                    {
                        employees.Add(employee);
                    }
                }

                return Ok(employees);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }
           
        }
        [HttpGet]
        public async Task<IActionResult> GetEmployeeDetailsById(string employeeId,string partitionKey)
        {

            try
            {
                var container = ContainerClient();
                ItemResponse<EmployeeModel> response = await container.ReadItemAsync<EmployeeModel>(employeeId, new PartitionKey(partitionKey));
                return Ok(response.Resource);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }

        }
        [HttpPut]
        public async Task<IActionResult> UpdateEmployee(EmployeeModel emp,string partitionKey)
        {

            try
            {

                var container = ContainerClient();
                ItemResponse<EmployeeModel> res = await container.ReadItemAsync<EmployeeModel>(emp.id, new PartitionKey(partitionKey));

                //Get Existing Item
                var existingItem = res.Resource;

                //Replace existing item values with new values 
                existingItem.Name = emp.Name;
                existingItem.Country = emp.Country;
                existingItem.City = emp.City;
                existingItem.Department = emp.Department;
                existingItem.Designation = emp.Designation;

              var updateRes=  await container.ReplaceItemAsync(existingItem, emp.id, new PartitionKey(partitionKey));

                return Ok(updateRes.Resource);

            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }
          
        }

        [HttpDelete]
        public async Task<IActionResult> DeleteEmployee(string empId, string partitionKey)
        {

            try
            {

                var container = ContainerClient();
               var response= await container.DeleteItemAsync<EmployeeModel>(empId, new PartitionKey(partitionKey));
                return Ok(response.StatusCode);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }
        }

    }
}

Now, we have all the code and required configuration to work with Azure CosmosDB in our sample application.

Step 12: Run the ASP.NET Core API Application

Now press Keyboard F5 or the Visual Studio Run button to run the application. After running the application, the following screen will be shown in the browser with swagger UI having all the methods which we have created in our ASP.NET core web API, as shown in the following screenshot:


Now, we will test the functionality by using the Swagger UI, but you can use Postman or any other tool to execute the API endpoints.

Step 13: Azure Cosmos DB CRUD Demo 

Watch the following animated image to see how the insert, read, update, and delete operations of Azure Cosmos DB work.

Add Employees


Get List of Employees and Employee by Id




Update the Employee


Delete the Employee by Id




Summary

I hope, from all the examples above, you have learned how to insert, read, update, and delete records in the Azure Cosmos DB SQL API using the ASP.NET Core Web API. If you like it, share it with your friends and subscribe to the blog and YouTube channel for more more articles.

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode