Azure

CRUD Operations In Azure Cosmos DB SQL API Utilizing ASP.NET Core Internet API C#

The Azure Cosmos DB is a NoSQL database that’s globally distributed and extremely accessible. The Azure Cosmos DB helps a number of sorts of payload buildings primarily based on the kind of API, together with the JSON format. The database is well scalable with a couple of clicks throughout the areas. The Cosmos DB helps the next API sorts:

  • SQL API
  • Cassandra API
  • Gremlin API
  • Desk API
  • MongoDB API

On this article, we are going to use the SQL API to carry out insert, replace, delete, and browse operations from the Cosmos DB utilizing the ASP.NET core Internet API with C#, so let’s begin step-by-step so freshmen may also perceive. The next is the circulation of our pattern software, which we’re going to create for the CRUD operations

Step 1: Arrange Conditions

Arrange the next one of many required pre-requisites to carry out the CRUD operation within the Azure Cosmos DB

  • Azure Subscription OR
  • Azure Cosmos DB Emulator 

Azure Subscription 

To create the Azure cloud Cosmos DB account, you want an energetic Azure subscription. Once you create the Cosmos DB account on the cloud, the Azure Cosmos DB Serverless account gives the primary 1000 RU and 25 GB of storage without cost per subscription. Seek advice from the next hyperlink to be taught the fundamentals and how you can create the Azure Cosmos DB account.

Azure Cosmos DB Emulator (offline)

As talked about above, the primary method requires an energetic Azure subscription in addition to an energetic web connection, which isn’t possible for everybody who simply needs to discover or be taught concerning the Azure Cosmos DB. To beat the previous situation, we are able to use the Azure Cosmos DB capabilities and options utilizing the Azure Cosmos DB Emulator with out an energetic Azure subscription or an energetic web connection. The Azure Cosmos DB Emulator at the moment doesn’t have help for all of the NoSQL APIs, however it’ll help probably the most generally used NoSQL APIs, such because the SQL API and Mongo DB API, and sooner or later it might additionally help all of the Cosmos DB APIs.

The next is the hyperlink to obtain the Azure Cosmos DB Emulator.

After clicking on the hyperlink, the official Microsoft documentation web site will get opened, from which you could find and set up the most recent model of the Azure Cosmos DB Emulator.

Step 2: Create Azure Cosmos DB 

As talked about in Step 1, I hope you arrange the required conditions from the supplied choices to create the Cosmos DB. On this article, we’re going to use the Azure Cosmos DB emulator as an alternative of a Cloud Azure Cosmos DB account.

After putting in the Cosmos DB emulator, seek for the Azure Cosmos DB emulator from the search bar of the window, which seems to be like the next:

CRUD Operations in Azure Cosmos DB SQL API Using ASP.NET Core Web API C#

The previous picture reveals the Azure CosmosDB Account of the emulator, which is able to present the identical options because the Cloud Azure CosmosDB Account for growth. Now click on on the explorer and create the database and container. The explorer will then appear like this:

CRUD Operations in Azure Cosmos DB SQL API Using ASP.NET Core Web API C#

We’re going to retailer the worker fundamental particulars in Azure CosmosDB, and we’re planning to make use of Division as a partition key and ID because the distinctive id for our worker data.

Be aware:

  • The ID and Division properties needs to be a part of your backend enter whereas inserting or updating the data; in any other case, you’re going to get the exceptions.

I hope you’ve gotten accomplished the required setup as defined on this article, together with the creation of the Azure Cosmos account and database.

Step 3: Create ASP.NET Core Internet API Venture

  1. Begin then All Applications and choose “Microsoft Visual Studio”.
  2. As soon as the Visual Studio Opens, then click on on Proceed With out Code.
  3. Then Go to Visual Studio Menu, click on on File => New Venture then select ASP.NET Core Internet API Venture Template.
  4. Then outline the challenge identify, location of the challenge, then click on on the subsequent button.
  5. On the subsequent display, present the extra particulars: framework, authentication sort, and examine the Allow Open API Help checkbox as proven beneath.

CRUD Operations in Azure Cosmos DB SQL API Using ASP.NET Core Web API C#

The previous steps will create the ASP.NET Core Internet API software and resolution explorer. It can appear like what’s proven within the following picture.

CRUD Operations in Azure Cosmos DB SQL API Using ASP.NET Core Web API C#

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

The Microsoft.Azure.Cosmos is the most recent nuget package deal to work together with the Azure Cosmos DB. The Microsoft.Azure.Cosmos helps fundamental to customized and sophisticated database operations, comply with the next steps so as to add the Nuget package deal.

  1. Proper click on on the Answer Explorer, discover Handle NuGet Package deal Supervisor and click on on it
  2. After as proven within the picture and kind in search field Microsoft.Azure.Cosmos
  3. Choose Microsoft.Azure.Cosmos as proven within the picture, 
  4. Select model of Microsoft.Azure.Cosmos library and click on on set up button

CRUD Operations in Azure Cosmos DB SQL API Using ASP.NET Core Web API C#

I hope you’ve gotten adopted the identical steps and put in Microsoft.Azure.Cosmos nuget package deal. The following step is to delete the default controller and mannequin class so we are able to begin from scratch.

Step 5: Create the Mannequin Class

  • First, delete the default mannequin class, which is created outdoors the folder construction, so we are able to begin from scratch. 
  • Subsequent, create the folder named Mannequin by right-clicking on the answer explorer.
  • Create the mannequin class Worker Mannequin by right-clicking on the Mannequin folder, as proven within the following picture

CRUD Operations in Azure Cosmos DB SQL API Using ASP.NET Core Web API C#

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

EmployeeModel.cs

namespace EmployeeManagement.Mannequin {
    public class EmployeeModel {
        public string ? id {
            get;
            set;
        }
        public string ? Identify {
            get;
            set;
        }
        public string ? Nation {
            get;
            set;
        }
        public string ? Metropolis {
            get;
            set;
        }
        public string ? Division {
            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 proven within the following picture.

CRUD Operations in Azure Cosmos DB SQL API Using ASP.NET Core Web API C#

After including the mannequin class and API controller class, the answer explorer will appear like the next:

CRUD Operations in Azure Cosmos DB SQL API Using ASP.NET Core Web API C#

Now open the EmployeeController.cs file and add the next configuration.

Outline the next route at controller stage, in order that we are able to add the a number of Get, Submit, Put, or Delete and keep away from the identify ambiguity exception.

[ApiController]
[Route("[api/[controller]/[action]]")]
public class EmployeeController: ControllerBase {}

Declare the next variable and set the Azure Cosmos DB configuration by copying the main points from step 2.

[ApiController]
[Route("api/[controller]/[action]")]
public class EmployeeController: ControllerBase {
    // Cosmos DB particulars, In actual use circumstances, these particulars needs to be configured in safe configuraion file.
    non-public readonly string CosmosDBAccountUri = "https://localhost:8081/";
    non-public readonly string CosmosDBAccountPrimaryKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
    non-public readonly string CosmosDbName = "EmployeeManagementDB";
    non-public readonly string CosmosDbContainerName = "Staff";
}

Step 7: Create a Methodology to Add Worker

Add the next code into the EmployeeController.cs class so as to add the workers into the CosmosDB. This technique takes enter values utilizing the EmployeeModel class. 

[HttpPost]
public async Process < IActionResult > AddEmployee(EmployeeModel worker) {
    attempt {
        var container = ContainerClient();
        var response = await container.CreateItemAsync(worker, new PartitionKey(worker.Division));
        return Okay(response);
    } catch (Exception ex) {
        return BadRequest(ex.Message);
    }
}

As defined in step 2, we’re passing the ID and Division as a partition key as a part of the worker enter payload whereas including the worker particulars. These parameters have to be a part of the enter parameter payload.

Step 8:  Create a Methodology to Get Staff

Add the next code into the EmployeeController.cs class to get all the workers from the Cosmos database.

[HttpGet]
public async Process < IActionResult > GetEmployeeDetails() {
    attempt {
        var container = ContainerClient();
        var sqlQuery = "SELECT * FROM c";
        QueryDefinition queryDefinition = new QueryDefinition(sqlQuery);
        FeedIterator < EmployeeModel > queryResultSetIterator = container.GetItemQueryIterator < EmployeeModel > (queryDefinition);
        Checklist < EmployeeModel > workers = new Checklist < EmployeeModel > ();
        whereas (queryResultSetIterator.HasMoreResults) {
            FeedResponse < EmployeeModel > currentResultSet = await queryResultSetIterator.ReadNextAsync();
            foreach(EmployeeModel worker in currentResultSet) {
                workers.Add(worker);
            }
        }
        return Okay(workers);
    } catch (Exception ex) {
        return BadRequest(ex.Message);
    }
}

This instance shouldn’t be observe since we’re fetching all the workers with out paging or a partition key filter, however we’re doing this to be taught the way it works with out making it difficult. Within the subsequent article, I’ll present how you can get an inventory of data with the paging.

Step 9: Create a Methodology to Get Worker by ID

Create the GetEmployeeDetailsById technique within the EmployeeController.cs and add the next code to get the worker by employeeId and partition key from the Cosmos database.

[HttpGet]
public async Process < IActionResult > GetEmployeeDetailsById(string employeeId, string partitionKey) {
    attempt {
        var container = ContainerClient();
        ItemResponse < EmployeeModel > response = await container.ReadItemAsync < EmployeeModel > (employeeId, new PartitionKey(partitionKey));
        return Okay(response.Useful resource);
    } catch (Exception ex) {
        return BadRequest(ex.Message);
    }
}

Step 10: Create a Methodology to Replace Worker

Create the UpdateEmployee technique within the EmployeeController.cs and add the next code to replace the worker by employeeId and partition key.

The CosmosDB doesn’t help the partial replace characteristic; slightly, it truly replaces the prevailing merchandise by getting the doc to be up to date and sending the identical particulars to the database after fields change or replace.

[HttpPut]
public async Process < IActionResult > UpdateEmployee(EmployeeModel emp, string partitionKey) {
    attempt {
        var container = ContainerClient();
        ItemResponse < EmployeeModel > res = await container.ReadItemAsync < EmployeeModel > (emp.id, new PartitionKey(partitionKey));
        //Get Present Merchandise
        var existingItem = res.Useful resource;
        //Change present merchandise values with new values 
        existingItem.Identify = emp.Identify;
        existingItem.Nation = emp.Nation;
        existingItem.Metropolis = emp.Metropolis;
        existingItem.Division = emp.Division;
        existingItem.Designation = emp.Designation;
        var updateRes = await container.ReplaceItemAsync(existingItem, emp.id, new PartitionKey(partitionKey));
        return Okay(updateRes.Useful resource);
    } catch (Exception ex) {
        return BadRequest(ex.Message);
    }
}

Step 11: Create a Methodology to Delete Worker

Create the DeleteEmployee technique within the EmployeeController.cs and add the next code to delete the worker by employeeId and partition key.

[HttpDelete]
public async Process < IActionResult > DeleteEmployee(string empId, string partitionKey) {
    attempt {
        var container = ContainerClient();
        var response = await container.DeleteItemAsync < EmployeeModel > (empId, new PartitionKey(partitionKey));
        return Okay(response.StatusCode);
    } catch (Exception ex) {
        return BadRequest(ex.Message);
    }
  }
}

All the code of the EmployeeController.cs class file will appear like the next after including all of the strategies collectively:

EmployeeController.cs

utilizing EmployeeManagement.Mannequin;
utilizing Microsoft.AspNetCore.Mvc;
utilizing Microsoft.Azure.Cosmos;
namespace EmployeeManagement.Controllers {
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class EmployeeController: ControllerBase {
        // Cosmos DB particulars, In actual use circumstances, these particulars needs to be configured in safe configuraion file.
        non-public readonly string CosmosDBAccountUri = "https://localhost:8081/";
        non-public readonly string CosmosDBAccountPrimaryKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
        non-public readonly string CosmosDbName = "EmployeeManagementDB";
        non-public readonly string CosmosDbContainerName = "Staff";
        /// <abstract>
        /// Commom Container Shopper, you may as well move the configuration paramter dynamically.
        /// </abstract>
        /// <returns> Container Shopper </returns>
        non-public Container ContainerClient() {
                CosmosClient cosmosDbClient = new CosmosClient(CosmosDBAccountUri, CosmosDBAccountPrimaryKey);
                Container containerClient = cosmosDbClient.GetContainer(CosmosDbName, CosmosDbContainerName);
                return containerClient;
            }
            [HttpPost]
        public async Process < IActionResult > AddEmployee(EmployeeModel worker) {
                attempt {
                    var container = ContainerClient();
                    var response = await container.CreateItemAsync(worker, new PartitionKey(worker.Division));
                    return Okay(response);
                } catch (Exception ex) {
                    return BadRequest(ex.Message);
                }
            }
            [HttpGet]
        public async Process < IActionResult > GetEmployeeDetails() {
                attempt {
                    var container = ContainerClient();
                    var sqlQuery = "SELECT * FROM c";
                    QueryDefinition queryDefinition = new QueryDefinition(sqlQuery);
                    FeedIterator < EmployeeModel > queryResultSetIterator = container.GetItemQueryIterator < EmployeeModel > (queryDefinition);
                    Checklist < EmployeeModel > workers = new Checklist < EmployeeModel > ();
                    whereas (queryResultSetIterator.HasMoreResults) {
                        FeedResponse < EmployeeModel > currentResultSet = await queryResultSetIterator.ReadNextAsync();
                        foreach(EmployeeModel worker in currentResultSet) {
                            workers.Add(worker);
                        }
                    }
                    return Okay(workers);
                } catch (Exception ex) {
                    return BadRequest(ex.Message);
                }
            }
            [HttpGet]
        public async Process < IActionResult > GetEmployeeDetailsById(string employeeId, string partitionKey) {
                attempt {
                    var container = ContainerClient();
                    ItemResponse < EmployeeModel > response = await container.ReadItemAsync < EmployeeModel > (employeeId, new PartitionKey(partitionKey));
                    return Okay(response.Useful resource);
                } catch (Exception ex) {
                    return BadRequest(ex.Message);
                }
            }
            [HttpPut]
        public async Process < IActionResult > UpdateEmployee(EmployeeModel emp, string partitionKey) {
                attempt {
                    var container = ContainerClient();
                    ItemResponse < EmployeeModel > res = await container.ReadItemAsync < EmployeeModel > (emp.id, new PartitionKey(partitionKey));
                    //Get Present Merchandise
                    var existingItem = res.Useful resource;
                    //Change present merchandise values with new values 
                    existingItem.Identify = emp.Identify;
                    existingItem.Nation = emp.Nation;
                    existingItem.Metropolis = emp.Metropolis;
                    existingItem.Division = emp.Division;
                    existingItem.Designation = emp.Designation;
                    var updateRes = await container.ReplaceItemAsync(existingItem, emp.id, new PartitionKey(partitionKey));
                    return Okay(updateRes.Useful resource);
                } catch (Exception ex) {
                    return BadRequest(ex.Message);
                }
            }
            [HttpDelete]
        public async Process < IActionResult > DeleteEmployee(string empId, string partitionKey) {
            attempt {
                var container = ContainerClient();
                var response = await container.DeleteItemAsync < EmployeeModel > (empId, new PartitionKey(partitionKey));
                return Okay(response.StatusCode);
            } catch (Exception ex) {
                return BadRequest(ex.Message);
            }
        }
    }
}

Now, now we have all of the code and required configuration to work with Azure CosmosDB in our pattern software.

Step 12: Run the ASP.NET Core API Software

Now press Keyboard F5 or the Visual Studio Run button to run the appliance. After working the appliance, the next display will probably be proven within the browser with swagger UI having all of the strategies which now we have created in our ASP.NET core net API, as proven within the following screenshot:

CRUD Operations in Azure Cosmos DB SQL API Using ASP.NET Core Web API C#

Now, we are going to check the performance through the use of the Swagger UI, however you should use Postman or another instrument to execute the API endpoints.

Step 13: Azure Cosmos DB CRUD Demo 

The next animated picture reveals how the insert, learn, replace, and delete operations of Azure Cosmos DB work.

Add Staff

CRUD Operations in Azure Cosmos DB SQL API Using ASP.NET Core Web API C#

Get Checklist of Staff and Worker by Id

CRUD Operations in Azure Cosmos DB SQL API Using ASP.NET Core Web API C#

Replace the Worker

CRUD Operations in Azure Cosmos DB SQL API Using ASP.NET Core Web API C#

Delete the Worker by Id

CRUD Operations in Azure Cosmos DB SQL API Using ASP.NET Core Web API C#

Abstract

I hope, from all of the examples above, you’ve gotten discovered how you can insert, learn, replace, and delete information from Azure Cosmos DB utilizing ASP.NET Core API C#. In the event you prefer it, share it with your folks and freshmen, or any doubts or strategies, then please these utilizing the remark field.

Learn extra articles on ASP.NET, 

Tags
Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Close