Using Azure Cosmos DB In MVC Web Application

Introduction 

 
Microsoft Azure Cosmos DB is a database service native to Azure that focuses on providing a high-performance database regardless of your selected API or data model.
 

Azure Cosmos DB storage APIs
 

Azure Cosmos DB can be accessed by using five different APIs. The underlying data structure in Azure Cosmos DB is a data model based on atom record sequences that enabled Azure Cosmos DB to support multiple data models.
 
Azure Cosmos DB will be able to support many more models and APIs over time.
  • MongoDB API 
  • Table API
  • Gremlin API
  • Apache Cassandra API
  • SQL API
In this article, we will focus on the use of the SQL API.
 
The SQL API in Azure Cosmos DB is a JavaScript and JavaScript Object Notation (JSON) native API based on the Azure Cosmos DB database engine. The SQL API also provides query capabilities rooted in the familiar SQL query language.
 

Create an Azure Cosmos DB account

 
Before writing the code, we need to create a Cosmos DB account, so let's create an Azure Cosmos DB account.
 
In a new browser window, sign in to the Azure portal.
 
Select Create a resource > Databases > Azure Cosmos DB.
 
On the Create Azure Cosmos DB Account page, enter the basic settings for the new Azure Cosmos DB account.
 
image1 
 
image2 
 
The account creation takes a few minutes. Wait for the portal to display the "Congratulations! Your Azure Cosmos DB account was created" page.
 
 image3
 

Create an MVC Web Application

 
Open Visual Studio 2017 on your computer. On the File menu, select New, and then choose Project.
 
In the New Project dialog, select Templates / Visual C# / Web/ ASP.NET Web Application (.NET Framework), name your project, and then select MVC and then click OK.
 
 image4
 
In the Solution Explorer, right click on your new web application, which is under your Visual Studio solution, and then click Manage NuGet Packages
 
In the NuGet tab, click Browse, and type Azure DocumentDB in the search box.
 
Within the results, find Microsoft.Azure.DocumentDB and click Install.
 image4
 
The project ready now to start writing some code. Let’s start.
 

Connect to an Azure Cosmos DB account
 

First, we need to create employee entity class in Models folder,
  1. public class Employee  
  2. {  
  3.     public string Name { getset; }  
  4.     public float Salary { getset; }  
  5.     public DateTime JoinDate { getset; }    
  6. }  
 In HomeController class add Employees Action 
  1. public ActionResult Employees()  
  2.         {  
  3.             return View();  
  4.         }  
Then, we need to add a View to the employee action.
 
image4  
 
add these references in HomeController.cs,
  1. using System.Net;  
  2. using Microsoft.Azure.Documents;  
  3. using Microsoft.Azure.Documents.Client;  
Now, add these two constants in constructor 
  1. string EndpointUrl;  
  2.     private string PrimaryKey;  
  3.     private DocumentClient client;  
  4.     public HomeController()  
  5.     {  
  6.         EndpointUrl = "<your endpoint URL>";  
  7.         PrimaryKey = "<your primary key>";  
  8.   
  9.     }  
Next, head back to the Azure portal to retrieve your endpoint URL and primary key. In the Azure portal, navigate to your Azure Cosmos DB account, and then click Keys.
 
image4  
 
Copy the URI from the portal and paste it into <your endpoint URL>. Then copy the PRIMARY KEY from the portal and paste it into <your primary key>.
  1. public HomeController()  
  2. {  
  3.     EndpointUrl = "https://youraccountname.documents.azure.com:443/";  
  4.     PrimaryKey = "F4tQtOfR8AWs6oy7E4ZbbbssqBxjqbL4EWQzoZQgKrZbyj1wT6ffdk6UjIjCQCwVRjp7vJcVQvwh8oVSJg==";  
  5.   
  6. }  
Next, we'll start the application by creating a new instance of the DocumentClient.
  1. public  HomeController()  
  2.     {  
  3.         EndpointUrl = "https:// youraccountname.documents.azure.com:443/";  
  4.         PrimaryKey = "F4tQtOfR8AWs6oy7E4ZjvQ3mr3R3OBxjqbL4EWQzoZQgKrZbyj1wT6ffdk6UjIjCQCwVRjp7vJcVQvwh8oVSJg==";  
  5.         client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey);  
  6.           
  7.     }  
Your Azure Cosmos DB database can be created by using the CreateDatabaseIfNotExistsAsync method of the DocumentClient class. A database is the logical container of JSON document storage partitioned across collections.
 
In Employees Action we need to call the CreateDatabaseIfNotExistsAsync.
  1. public async Task<ActionResult> Employees()  
  2.       {  
  3.           await this.client.CreateDatabaseIfNotExistsAsync(new Database { Id = "HRDB" });  
  4.           return View();  
  5.       }  
You have successfully created an Azure Cosmos DB database.
 

Create a collection

 
A collection can be created by using the CreateDocumentCollectionIfNotExistsAsync method of the DocumentClient class. A collection is a container of JSON documents and associated JavaScript application logic.
 
Inside Employee action add the following code,
  1. await this.client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("HRDB"),  
  2.               new DocumentCollection { Id = "EmployeesCollection" });  

Query Azure Cosmos DB

 
Azure Cosmos DB supports rich queries against JSON documents stored in each collection.
 
Azure Cosmos DB SQL syntax as well as LINQ. This is a simple Query that returns all employee where employee salary less than 100.
  1. FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1 };  
  2.   
  3.           
  4.     IQueryable<Employee> employeeQuery = this.client.CreateDocumentQuery<Employee>(  
  5.                   UriFactory.CreateDocumentCollectionUri("HRDB""EmployeesCollection"), queryOptions)  
  6.                   .Where(f => f.Salary >= 100);  

Create JSON documents

 
A document can be created by using the CreateDocumentAsync method of the DocumentClient class. Documents are user-defined (arbitrary) JSON content.
 
We can now insert one or more documents. First, we need to create an employee action in the home controller.
  1. public ActionResult AddEmployee()  
  2.       {  
  3.           return View();  
  4.       }  
  5.   
  6.       [HttpPost]  
  7.       public async Task<ActionResult> AddEmployee(Employee employee)  
  8.       {  
  9.           await this.client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri("HRDB""EmployeesCollection"), employee);  
  10.           return RedirectToAction("Employees");  
  11.       }  
Then, add a View to add employee action.
 
image4  
 
 Now, run your application and test it.
 
image4  
 

Delete JSON document

 
Azure Cosmos DB supports deleting JSON documents. We need to create an action for deleting the employee as in the following:
  1. public async Task<ActionResult> DeleteEmployee(string documentId)  
  2.         {  
  3.             await this.client.DeleteDocumentAsync(UriFactory.CreateDocumentUri("HRDB""EmployeesCollection", documentId));  
  4.             return RedirectToAction("Employees");  
  5.         }  
Congratulations! Your application is ready now.
 
Here is the full source code. And you can download the full project source code. ๐Ÿ˜Š
  1. public class Employee  
  2.     {  
  3.         [JsonProperty(PropertyName = "id")]  
  4.         public string Id { getset; }  
  5.         public string Name { getset; }  
  6.         public float Salary { getset; }  
  7.         public DateTime JoinDate { getset; }    
  8.     }  
  9.   
  10. public class HomeController : Controller  
  11.     {  
  12.   
  13.         string EndpointUrl;  
  14.         private string PrimaryKey;  
  15.         private DocumentClient client;  
  16.         public HomeController()  
  17.         {  
  18.             EndpointUrl = "https://sbeehlab.documents.azure.com:443/";  
  19.             PrimaryKey = "F4tQtOfR8AWs6oy7E4ZjvQ3mr3R3OBxjqbL4EWQzoZQgKrZbyj1wT6ffdk6UjIjCQCwVRjp7vJcVQvwh8oVSJg==";  
  20.   
  21.   
  22.             client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey);  

  23.         }  
  24.         public ActionResult Index()  
  25.         {  
  26.             return View();  
  27.         }  
  28.   
  29.         public ActionResult About()  
  30.         {  
  31.             ViewBag.Message = "Your application description page.";  
  32.   
  33.             return View();  
  34.         }  
  35.   
  36.         public ActionResult Contact()  
  37.         {  
  38.             ViewBag.Message = "Your contact page.";  
  39.   
  40.             return View();  
  41.         }  
  42.         public async Task<ActionResult> Employees()  
  43.         {  
  44.             await client.CreateDatabaseIfNotExistsAsync(new Database { Id = "HRDB" });  
  45.   
  46.             await client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("HRDB"),  
  47.                 new DocumentCollection { Id = "EmployeesCollection" });  
  48.   
  49.   
  50.             FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1 };  
  51.   
  52.   
  53.             IQueryable<Employee> employeeQuery = this.client.CreateDocumentQuery<Employee>(  
  54.                     UriFactory.CreateDocumentCollectionUri("HRDB""EmployeesCollection"), queryOptions)  
  55.                     .Where(f => f.Salary >= 100);  
  56.   
  57.             return View(employeeQuery);  
  58.         }  
  59.   
  60.         public ActionResult AddEmployee()  
  61.         {  
  62.             return View();  
  63.         }  
  64.   
  65.         [HttpPost]  
  66.         public async Task<ActionResult> AddEmployee(Employee employee)  
  67.         {  
  68.   
  69.             await this.client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri("HRDB""EmployeesCollection"), employee);  
  70.   
  71.             return RedirectToAction("Employees");  
  72.         }  
  73.   
  74.         public async Task<ActionResult> DeleteEmployee(string documentId)  
  75.         {  
  76.             await this.client.DeleteDocumentAsync(UriFactory.CreateDocumentUri("HRDB""EmployeesCollection", documentId));  
  77.             return RedirectToAction("Employees");  
  78.         }  
  79.     }  


Similar Articles