Connecting The Same Cosmos DB Database Using SQL API And Mongo API From A Blazor App

Introduction to Cosmos DB

If you look at the metadata information of any collection in Cosmos DB, you can find the following metadata properties in both, the SQL API and MongoDB API.

  • _rid: auto-generated resource id
  • _ts: auto-generated timestamp (last updated) epoch value
  • _etag: auto-generated GUID. Used for optimistic concurrency
  • _self: auto-generated URI path to the resource. This is very useful when using with SQL API for Azure Cosmos DB
  • _attachments: URI path suffix to the resource attachment

For those who are new to Cosmos DB, Azure Cosmos DB is Microsoft’s globally distributed, multi-model database. With the click of a button, Azure Cosmos DB enables you to elastically and independently scale throughput and storage across any number of Azure’s geographic regions. It offers throughput, latency, availability, and consistency guarantees with comprehensive service level agreements (SLAs), something no other database service can offer. Currently, there are five different types of APIs supported by Cosmos DB, as given below.

You can also refer to the below article to read more about Cosmos DB.

About Blazor Framework

As per Microsoft’s documentation about Blazor, it is an experimental .NET web framework using C#/Razor and HTML that runs in the browser with WebAssembly. Blazor provides all the benefits of a client-side web UI framework using .NET on the client and optionally, on the server.

You can refer to the below articles about Blazor to get more details.

Create a Blazor application in Visual Studio 2017 Community

 
Open Visual Studio and choose “Create New project” and select ASP.NET Core Web Application. Please give a valid name to your project.
 
 
 
Currently, there are three types of Blazor templates available. We are going with Blazor (ASP.NET Core hosted) template.
 
 
Our application will be created in a moment. If we look at the solution structure, we can see there are three projects created under our solution - “Client”, “Server” and “Shared”.
 
 

By default, Blazor created some files in these three projects. We can remove all the unwanted files like “Counter.cshtml”, “FetchData.cshtml”, “SurveyPrompt.cshtml” from the Client project and “SampleDataController.cs” file from Server project and delete “WeatherForecast.cs” file from the Shared project too.

We can create a “Models” folder in the “Shared” project and create an “Employee” class under this folder. As we are creating a simple Employee app, we must provide all the required properties inside this class.

We are creating a common model for both, SQL and Mongo APIs. For MongoDB API, we need BsonTypeObjectId and BsonId. For that, we must install “MongoDB.Driver” NuGet package in the Shared project.
 
 
We must install “Newtonsoft.Json” for serializing the class objects and properties.
 
 
Employee.cs
  1. using MongoDB.Bson;  
  2. using MongoDB.Bson.Serialization.Attributes;  
  3. using Newtonsoft.Json;  
  4. namespace BlazorCosmosDBSQLandMongo.Shared.Models  
  5. {  
  6.     public class Employee  
  7.     {  
  8.         [JsonProperty(PropertyName = "id")]  
  9.         [BsonId]  
  10.         [BsonRepresentation(BsonType.ObjectId)]  
  11.         public string Id { getset; }  
  12.         [JsonProperty(PropertyName = "name")]  
  13.         public string Name { getset; }  
  14.         [JsonProperty(PropertyName = "address")]  
  15.         public string Address { getset; }  
  16.         [JsonProperty(PropertyName = "gender")]  
  17.         public string Gender { getset; }  
  18.         [JsonProperty(PropertyName = "company")]  
  19.         public string Company { getset; }  
  20.         [JsonProperty(PropertyName = "designation")]  
  21.         public string Designation { getset; }  
  22.     }  
  23. }  

We are using separate providers for SQL API and Mongo API. Let us go to “Server” project and create a new “DataAccess” folder.

We can create a common “IDataAccessProvider” interface. We will create separate data access providers for SQL API and Mongo API using this interface.

IDataAccessProvider.cs

  1. using BlazorCosmosDBSQLandMongo.Shared.Models;  
  2. using System.Collections.Generic;  
  3. using System.Threading.Tasks;  
  4. namespace BlazorCosmosDBSQLandMongo.Server.DataAccess  
  5. {  
  6.     public interface IDataAccessProvider  
  7.     {  
  8.         Task Add(Employee employee);  
  9.         Task Update(Employee employee);  
  10.         Task Delete(string id);  
  11.         Task<Employee> GetEmployee(string id);  
  12.         Task<IEnumerable<Employee>> GetEmployees();  
  13.     }  
  14. }  

We must installMongoDB.Driver” NuGet package again  for this “Server” project for Mongo API. Also install “Microsoft.Azure.DocumentDB.Core” for SQL API.

 
Please note, I have used .NET Core 2.1 version in this project. So, I am using the previous version of (v2.0.0) DocumentDB.Core NuGet.
 
The current version (when writing this article) is v2.2.2.
 
 
We can create “SqlApiRepository” generic class now. This class will be used in the data access provider class later.
 
SqlApiRepository.cs
  1. using Microsoft.Azure.Documents;  
  2. using Microsoft.Azure.Documents.Client;  
  3. using Microsoft.Azure.Documents.Linq;  
  4. using System;  
  5. using System.Collections.Generic;  
  6. using System.Threading.Tasks;  
  7. namespace BlazorCosmosDBSQLandMongo.Server.DataAccess  
  8. {  
  9.     public static class SqlApiRepository<T> where T : class  
  10.     {  
  11.         private static readonly string Endpoint = "https://localhost:8081/";  
  12.         private static readonly string Key = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";  
  13.         private static readonly string DatabaseId = "SarathCosmosDB";  
  14.         private static readonly string CollectionId = "EmployeeSQL";  
  15.         private static DocumentClient client;  
  16.         public static void Initialize()  
  17.         {  
  18.             client = new DocumentClient(new Uri(Endpoint), Key, new ConnectionPolicy { EnableEndpointDiscovery = false });  
  19.             CreateDatabaseIfNotExistsAsync().Wait();  
  20.             CreateCollectionIfNotExistsAsync(CollectionId).Wait();  
  21.         }  
  22.         private static async Task CreateDatabaseIfNotExistsAsync()  
  23.         {  
  24.             try  
  25.             {  
  26.                 await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(DatabaseId));  
  27.             }  
  28.             catch (DocumentClientException e)  
  29.             {  
  30.                 if (e.StatusCode == System.Net.HttpStatusCode.NotFound)  
  31.                 {  
  32.                     await client.CreateDatabaseAsync(new Database { Id = DatabaseId });  
  33.                 }  
  34.                 else  
  35.                 {  
  36.                     throw;  
  37.                 }  
  38.             }  
  39.         }  
  40.         private static async Task CreateCollectionIfNotExistsAsync(string collectionId)  
  41.         {  
  42.             try  
  43.             {  
  44.                 await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, collectionId));  
  45.             }  
  46.             catch (DocumentClientException e)  
  47.             {  
  48.                 if (e.StatusCode == System.Net.HttpStatusCode.NotFound)  
  49.                 {  
  50.                     await client.CreateDocumentCollectionAsync(  
  51.                         UriFactory.CreateDatabaseUri(DatabaseId),  
  52.                         new DocumentCollection { Id = collectionId },  
  53.                         new RequestOptions { OfferThroughput = 1000 });  
  54.                 }  
  55.                 else  
  56.                 {  
  57.                     throw;  
  58.                 }  
  59.             }  
  60.         }  
  61.         public static async Task<T> GetSingleItemAsync(string id, string collectionId)  
  62.         {  
  63.             try  
  64.             {  
  65.                 Document document = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, collectionId, id));  
  66.                 return (T)(dynamic)document;  
  67.             }  
  68.             catch (DocumentClientException e)  
  69.             {  
  70.                 if (e.StatusCode == System.Net.HttpStatusCode.NotFound)  
  71.                 {  
  72.                     return null;  
  73.                 }  
  74.                 else  
  75.                 {  
  76.                     throw;  
  77.                 }  
  78.             }  
  79.         }  
  80.         public static async Task<IEnumerable<T>> GetItemsAsync(string collectionId)  
  81.         {  
  82.             IDocumentQuery<T> query = client.CreateDocumentQuery<T>(  
  83.                 UriFactory.CreateDocumentCollectionUri(DatabaseId, collectionId),  
  84.                 new FeedOptions { MaxItemCount = -1 })  
  85.                 .AsDocumentQuery();  
  86.             List<T> results = new List<T>();  
  87.             while (query.HasMoreResults)  
  88.             {  
  89.                 results.AddRange(await query.ExecuteNextAsync<T>());  
  90.             }  
  91.             return results;  
  92.         }  
  93.         public static async Task<Document> CreateItemAsync(T item, string collectionId)  
  94.         {  
  95.             return await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, collectionId), item);  
  96.         }  
  97.         public static async Task<Document> UpdateItemAsync(string id, T item, string collectionId)  
  98.         {  
  99.             return await client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, collectionId, id), item);  
  100.         }  
  101.         public static async Task DeleteItemAsync(string id, string collectionId)  
  102.         {  
  103.             await client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, collectionId, id));  
  104.         }  
  105.     }  
  106. }  

Please note, we have hard coded the connection endpoint and account key in the above class.

We can create “SqlApiProvider” class now. This class will inherit the “IDataAccessProvider” interface.
 
SqlApiProvider.cs
  1. using BlazorCosmosDBSQLandMongo.Shared.Models;  
  2. using System.Collections.Generic;  
  3. using System.Threading.Tasks;  
  4. namespace BlazorCosmosDBSQLandMongo.Server.DataAccess  
  5. {  
  6.     public class SqlApiProvider : IDataAccessProvider  
  7.     {  
  8.         private static readonly string CollectionId = "EmployeeSQL";  
  9.         public async Task Add(Employee employee)  
  10.         {  
  11.             try  
  12.             {  
  13.                 await SqlApiRepository<Employee>.CreateItemAsync(employee, CollectionId);  
  14.             }  
  15.             catch  
  16.             {  
  17.                 throw;  
  18.             }  
  19.         }  
  20.         public async Task<Employee> GetEmployee(string id)  
  21.         {  
  22.             try  
  23.             {  
  24.                 return await SqlApiRepository<Employee>.GetSingleItemAsync(id, CollectionId);  
  25.             }  
  26.             catch  
  27.             {  
  28.                 throw;  
  29.             }  
  30.         }  
  31.         public async Task<IEnumerable<Employee>> GetEmployees()  
  32.         {  
  33.             try  
  34.             {  
  35.                 return await SqlApiRepository<Employee>.GetItemsAsync(CollectionId);  
  36.             }  
  37.             catch  
  38.             {  
  39.                 throw;  
  40.             }  
  41.         }  
  42.         public async Task Update(Employee employee)  
  43.         {  
  44.             try  
  45.             {  
  46.                 await SqlApiRepository<Employee>.UpdateItemAsync(employee.Id, employee, CollectionId);  
  47.             }  
  48.             catch  
  49.             {  
  50.                 throw;  
  51.             }  
  52.         }  
  53.         public async Task Delete(string id)  
  54.         {  
  55.             try  
  56.             {  
  57.                 await SqlApiRepository<Employee>.DeleteItemAsync(id, CollectionId);  
  58.             }  
  59.             catch  
  60.             {  
  61.                 throw;  
  62.             }  
  63.         }  
  64.     }  
  65. }  

For Mongo API, we create a Mongo DB context file and create a data access provider.

MongoApiContext.cs
  1. using BlazorCosmosDBSQLandMongo.Shared.Models;  
  2. using MongoDB.Driver;  
  3. namespace BlazorCosmosDBSQLandMongo.Server.DataAccess  
  4. {  
  5.     public class MongoApiContext  
  6.     {  
  7.         private readonly IMongoDatabase _mongoDb;  
  8.         public MongoApiContext()  
  9.         {  
  10.             var client = new MongoClient("mongodb://localhost:C2y6yDjf5%2FR%2Bob0N8A7Cgv30VRDJIWEHLM%2B4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw%2FJw%3D%3D@localhost:10255/admin?ssl=true");  
  11.             _mongoDb = client.GetDatabase("SarathCosmosDB");  
  12.         }  
  13.         public IMongoCollection<Employee> Employee  
  14.         {  
  15.             get  
  16.             {  
  17.                 return _mongoDb.GetCollection<Employee>("EmployeeMongo");  
  18.             }  
  19.         }  
  20.     }  
  21. }  

We can create “MongoApiProvider” class and inherit “IDataAccessProvider” interface to this class.

MongoApiProvider.cs
  1. using BlazorCosmosDBSQLandMongo.Shared.Models;  
  2. using MongoDB.Driver;  
  3. using System.Collections.Generic;  
  4. using System.Threading.Tasks;  
  5. namespace BlazorCosmosDBSQLandMongo.Server.DataAccess  
  6. {  
  7.     public class MongoApiProvider : IDataAccessProvider  
  8.     {  
  9.         MongoApiContext db = new MongoApiContext();  
  10.         public async Task Add(Employee employee)  
  11.         {  
  12.             try  
  13.             {  
  14.                 await db.Employee.InsertOneAsync(employee);  
  15.             }  
  16.             catch  
  17.             {  
  18.                 throw;  
  19.             }  
  20.         }  
  21.         public async Task<Employee> GetEmployee(string id)  
  22.         {  
  23.             try  
  24.             {  
  25.                 FilterDefinition<Employee> filter = Builders<Employee>.Filter.Eq("Id", id);  
  26.                 return await db.Employee.Find(filter).FirstOrDefaultAsync();  
  27.             }  
  28.             catch  
  29.             {  
  30.                 throw;  
  31.             }  
  32.         }  
  33.         public async Task<IEnumerable<Employee>> GetEmployees()  
  34.         {  
  35.             try  
  36.             {  
  37.                 return await db.Employee.Find(_ => true).ToListAsync();  
  38.             }  
  39.             catch  
  40.             {  
  41.                 throw;  
  42.             }  
  43.         }  
  44.         public async Task Update(Employee employee)  
  45.         {  
  46.             try  
  47.             {  
  48.                 await db.Employee.ReplaceOneAsync(filter: g => g.Id == employee.Id, replacement: employee);  
  49.             }  
  50.             catch  
  51.             {  
  52.                 throw;  
  53.             }  
  54.         }  
  55.         public async Task Delete(string id)  
  56.         {  
  57.             try  
  58.             {  
  59.                 FilterDefinition<Employee> data = Builders<Employee>.Filter.Eq("Id", id);  
  60.                 await db.Employee.DeleteOneAsync(data);  
  61.             }  
  62.             catch  
  63.             {  
  64.                 throw;  
  65.             }  
  66.         }  
  67.     }  
  68. }  

Let us create “EmployeesController” controller file and add all the CRUD actions logic inside this file.

EmployeesController.cs
  1. using BlazorCosmosDBSQLandMongo.Server.DataAccess;  
  2. using BlazorCosmosDBSQLandMongo.Shared.Models;  
  3. using Microsoft.AspNetCore.Mvc;  
  4. using System.Collections.Generic;  
  5. using System.Threading.Tasks;  
  6. namespace BlazorCosmosDBSQLandMongo.Server.Controllers  
  7. {  
  8.     public class EmployeesController : Controller  
  9.     {  
  10.         private readonly IDataAccessProvider _dataAccessProvider;  
  11.         public EmployeesController(IDataAccessProvider dataAccessProvider)  
  12.         {  
  13.             _dataAccessProvider = dataAccessProvider;  
  14.         }  
  15.         [HttpGet]  
  16.         [Route("api/Employees/Get")]  
  17.         public async Task<IEnumerable<Employee>> Get()  
  18.         {  
  19.             return await _dataAccessProvider.GetEmployees();  
  20.         }  
  21.         [HttpPost]  
  22.         [Route("api/Employees/Create")]  
  23.         public async Task CreateAsync([FromBody]Employee employee)  
  24.         {  
  25.             if (ModelState.IsValid)  
  26.             {  
  27.                 await _dataAccessProvider.Add(employee);  
  28.             }  
  29.         }  
  30.         [HttpGet]  
  31.         [Route("api/Employees/Details/{id}")]  
  32.         public async Task<Employee> Details(string id)  
  33.         {  
  34.             var result = await _dataAccessProvider.GetEmployee(id);  
  35.             return result;  
  36.         }  
  37.         [HttpPut]  
  38.         [Route("api/Employees/Edit")]  
  39.         public async Task EditAsync([FromBody]Employee employee)  
  40.         {  
  41.             if (ModelState.IsValid)  
  42.             {  
  43.                 await _dataAccessProvider.Update(employee);  
  44.             }  
  45.         }  
  46.         [HttpDelete]  
  47.         [Route("api/Employees/Delete/{id}")]  
  48.         public async Task DeleteConfirmedAsync(string id)  
  49.         {  
  50.             await _dataAccessProvider.Delete(id);  
  51.         }  
  52.     }  
  53. }  

Startup.cs

  1. using BlazorCosmosDBSQLandMongo.Server.DataAccess;  
  2. using BlazorCosmosDBSQLandMongo.Shared.Models;  
  3. using Microsoft.AspNetCore.Blazor.Server;  
  4. using Microsoft.AspNetCore.Builder;  
  5. using Microsoft.AspNetCore.Hosting;  
  6. using Microsoft.AspNetCore.ResponseCompression;  
  7. using Microsoft.Extensions.DependencyInjection;  
  8. using System.Linq;  
  9. using System.Net.Mime;  
  10. namespace BlazorCosmosDBSQLandMongo.Server  
  11. {  
  12.     public class Startup  
  13.     {  
  14.         public void ConfigureServices(IServiceCollection services)  
  15.         {  
  16.             services.AddMvc();  
  17.             services.AddResponseCompression(options =>  
  18.             {  
  19.                 options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[]  
  20.                 {  
  21.                     MediaTypeNames.Application.Octet,  
  22.                     WasmMediaTypeNames.Application.Wasm,  
  23.                 });  
  24.             });  
  25.             services.AddScoped<IDataAccessProvider, SqlApiProvider>();  
  26.             //services.AddScoped<IDataAccessProvider, MongoApiProvider>();  
  27.         }  
  28.         public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  29.         {  
  30.             app.UseResponseCompression();  
  31.             if (env.IsDevelopment())  
  32.             {  
  33.                 app.UseDeveloperExceptionPage();  
  34.             }  
  35.             app.UseMvc(routes =>  
  36.             {  
  37.                 routes.MapRoute(name: "default", template: "{controller}/{action}/{id?}");  
  38.             });  
  39.             SqlApiRepository<Employee>.Initialize();  
  40.             app.UseBlazor<Client.Program>();  
  41.         }  
  42.     }  
  43. }  

I have injected two services here. Based on which API we choose, we can change. The same codebase will be working for both SQL API and Mongo API. Please note, I have commented the Mongo service now. After testing SQL API, I will comment SQL service and uncomment Mongo service.

We can go to the “Client” project and create 4 Razor views for CRUD actions.
 
ListEmployees.cshtml
  1. @using BlazorCosmosDBSQLandMongo.Shared.Models  
  2. @page "/listemployees"  
  3. @inject HttpClient Http  
  4. <p>  
  5.     <a href="/addemployee">Create New Employee</a>  
  6. </p>  
  7. @if (employees == null)  
  8. {  
  9.     <p><em>Loading...</em></p>  
  10. }  
  11. else  
  12. {  
  13.     <table class='table'>  
  14.         <thead>  
  15.             <tr>  
  16.                 <th>Name</th>  
  17.                 <th>Address</th>  
  18.                 <th>Gender</th>  
  19.                 <th>Company</th>  
  20.                 <th>Designation</th>  
  21.             </tr>  
  22.         </thead>  
  23.         <tbody>  
  24.             @foreach (var employee in employees)  
  25.             {  
  26.                 <tr>  
  27.                     <td>@employee.Name</td>  
  28.                     <td>@employee.Address</td>  
  29.                     <td>@employee.Gender</td>  
  30.                     <td>@employee.Company</td>  
  31.                     <td>@employee.Designation</td>  
  32.                     <td>  
  33.                         <a href='/editemployee/@employee.Id'>Edit</a>  |  
  34.                         <a href='/deleteemployee/@employee.Id'>Delete</a>  
  35.                     </td>  
  36.                 </tr>  
  37.             }  
  38.         </tbody>  
  39.     </table>  
  40. }  
  41. @functions {  
  42. Employee[] employees;  
  43. protected override async Task OnInitAsync()  
  44. {  
  45.     employees = await Http.GetJsonAsync<Employee[]>  
  46. ("/api/Employees/Get");  
  47. }  
  48. }  

AddEmployee.cshtml

  1. @using BlazorCosmosDBSQLandMongo.Shared.Models  
  2. @page "/addemployee"  
  3. @inject HttpClient Http  
  4. @inject Microsoft.AspNetCore.Blazor.Services.IUriHelper UriHelper  
  5. <h3>Create Employee</h3>  
  6. <hr />  
  7. <div class="row">  
  8.     <div class="col-md-4">  
  9.         <form>  
  10.             <div class="form-group">  
  11.                 <label for="Name" class="control-label">Name</label>  
  12.                 <input for="Name" class="form-control" bind="@employee.Name" />  
  13.             </div>  
  14.             <div class="form-group">  
  15.                 <label for="Address" class="control-label">Address</label>  
  16.                 <input for="Address" class="form-control" bind="@employee.Address" />  
  17.             </div>  
  18.             <div class="form-group">  
  19.                 <label for="Gender" class="control-label">Gender</label>  
  20.                 <select for="Gender" class="form-control" bind="@employee.Gender">  
  21.                     <option value="">-- Select Gender --</option>  
  22.                     <option value="Male">Male</option>  
  23.                     <option value="Female">Female</option>  
  24.                 </select>  
  25.             </div>  
  26.             <div class="form-group">  
  27.                 <label for="Company" class="control-label">Company</label>  
  28.                 <input for="Company" class="form-control" bind="@employee.Company" />  
  29.             </div>  
  30.             <div class="form-group">  
  31.                 <label for="Designation" class="control-label">Designation</label>  
  32.                 <input for="Designation" class="form-control" bind="@employee.Designation" />  
  33.             </div>  
  34.             <div class="form-group">  
  35.                 <input type="button" class="btn btn-default" onclick="@(async () => await CreateEmployee())" value="Save" />  
  36.                 <input type="button" class="btn" onclick="@Cancel" value="Cancel" />  
  37.             </div>  
  38.         </form>  
  39.     </div>  
  40. </div>  
  41. @functions {  
  42. Employee employee = new Employee();  
  43. protected async Task CreateEmployee()  
  44. {  
  45.     await Http.SendJsonAsync(HttpMethod.Post, "/api/Employees/Create", employee);  
  46.     UriHelper.NavigateTo("/listemployees");  
  47. }  
  48. void Cancel()  
  49. {  
  50.     UriHelper.NavigateTo("/listemployees");  
  51. }  
  52. }  

EditEmployee.cshtml

  1. @using BlazorCosmosDBSQLandMongo.Shared.Models  
  2. @page "/editemployee/{empId}"  
  3. @inject HttpClient Http  
  4. @inject Microsoft.AspNetCore.Blazor.Services.IUriHelper UriHelper  
  5. <h3>Edit Employee</h3>  
  6. <hr />  
  7. <div class="row">  
  8.     <div class="col-md-4">  
  9.         <form>  
  10.             <div class="form-group">  
  11.                 <label for="Name" class="control-label">Name</label>  
  12.                 <input for="Name" class="form-control" bind="@employee.Name" />  
  13.             </div>  
  14.             <div class="form-group">  
  15.                 <label for="Address" class="control-label">Address</label>  
  16.                 <input for="Address" class="form-control" bind="@employee.Address" />  
  17.             </div>  
  18.             <div class="form-group">  
  19.                 <label for="Gender" class="control-label">Gender</label>  
  20.                 <select for="Gender" class="form-control" bind="@employee.Gender">  
  21.                     <option value="">-- Select Gender --</option>  
  22.                     <option value="Male">Male</option>  
  23.                     <option value="Female">Female</option>  
  24.                 </select>  
  25.             </div>  
  26.             <div class="form-group">  
  27.                 <label for="Company" class="control-label">Company</label>  
  28.                 <input for="Company" class="form-control" bind="@employee.Company" />  
  29.             </div>  
  30.             <div class="form-group">  
  31.                 <label for="Designation" class="control-label">Designation</label>  
  32.                 <input for="Designation" class="form-control" bind="@employee.Designation" />  
  33.             </div>  
  34.             <div class="form-group">  
  35.                 <input type="button" value="Save" onclick="@(async () => await UpdateEmployee())" class="btn btn-default" />  
  36.                 <input type="button" value="Cancel" onclick="@Cancel" class="btn" />  
  37.             </div>  
  38.         </form>  
  39.     </div>  
  40. </div>  
  41. @functions {  
  42. [Parameter]  
  43. string empId { getset; }  
  44. Employee employee = new Employee();  
  45. protected override async Task OnInitAsync()  
  46. {  
  47.     employee = await Http.GetJsonAsync<Employee>("/api/Employees/Details/" + empId);  
  48. }  
  49. protected async Task UpdateEmployee()  
  50. {  
  51.     await Http.SendJsonAsync(HttpMethod.Put, "api/Employees/Edit", employee);  
  52.     UriHelper.NavigateTo("/listemployees");  
  53. }  
  54. void Cancel()  
  55. {  
  56.     UriHelper.NavigateTo("/listemployees");  
  57. }  
  58. }  

DeleteEmployee.cshtml

  1. @using BlazorCosmosDBSQLandMongo.Shared.Models  
  2. @page "/deleteemployee/{empId}"  
  3. @inject HttpClient Http  
  4. @inject Microsoft.AspNetCore.Blazor.Services.IUriHelper UriHelper  
  5. <h3>Delete Employee</h3>  
  6. <p>Are you sure you want to delete this employee with id :<b> @empId</b></p>  
  7. <br />  
  8. <div class="col-md-4">  
  9.     <table class="table">  
  10.         <tr>  
  11.             <td>Name</td>  
  12.             <td>@employee.Name</td>  
  13.         </tr>  
  14.         <tr>  
  15.             <td>Address</td>  
  16.             <td>@employee.Address</td>  
  17.         </tr>  
  18.         <tr>  
  19.             <td>Gender</td>  
  20.             <td>@employee.Gender</td>  
  21.         </tr>  
  22.         <tr>  
  23.             <td>Company</td>  
  24.             <td>@employee.Company</td>  
  25.         </tr>  
  26.         <tr>  
  27.             <td>Designation</td>  
  28.             <td>@employee.Designation</td>  
  29.         </tr>  
  30.     </table>  
  31.     <div class="form-group">  
  32.         <input type="button" value="Delete" onclick="@(async () => await Delete())" class="btn btn-default" />  
  33.         <input type="button" value="Cancel" onclick="@Cancel" class="btn" />  
  34.     </div>  
  35. </div>  
  36. @functions {  
  37. [Parameter]  
  38. string empId { getset; }  
  39. Employee employee = new Employee();  
  40. protected override async Task OnInitAsync()  
  41. {  
  42.     employee = await Http.GetJsonAsync<Employee>  
  43. ("/api/Employees/Details/" + empId);  
  44. }  
  45. protected async Task Delete()  
  46. {  
  47.     await Http.DeleteAsync("api/Employees/Delete/" + empId);  
  48.     UriHelper.NavigateTo("/listemployees");  
  49. }  
  50. void Cancel()  
  51. {  
  52.     UriHelper.NavigateTo("/listemployees");  
  53. }  
  54. }  

We can modify “NavMenu.cshtml” view under "Shared" folder as well.

NavMenu.cshtml
  1. <div class="top-row pl-4 navbar navbar-dark">  
  2.     <a class="navbar-brand" href="">Employee SPA App</a>  
  3.     <button class="navbar-toggler" onclick=@ToggleNavMenu>  
  4.         <span class="navbar-toggler-icon"></span>  
  5.     </button>  
  6. </div>  
  7. <div class=@(collapseNavMenu ? "collapse" : null) onclick=@ToggleNavMenu>  
  8.     <ul class="nav flex-column">  
  9.         <li class="nav-item px-3">  
  10.             <NavLink class="nav-link" href="" Match=NavLinkMatch.All>  
  11.                 <span class="oi oi-home" aria-hidden="true"></span> Home  
  12.             </NavLink>  
  13.         </li>  
  14.         <li class="nav-item px-3">  
  15.             <NavLink class="nav-link" href="/listemployees">  
  16.                 <span class="oi oi-list-rich" aria-hidden="true"></span> Employee Details  
  17.             </NavLink>  
  18.         </li>  
  19.     </ul>  
  20. </div>  
  21. @functions {  
  22. bool collapseNavMenu = true;  
  23. void ToggleNavMenu()  
  24. {  
  25.     collapseNavMenu = !collapseNavMenu;  
  26. }  
  27. }  

We can modify “Index.cshtml” also.

Index.cshtml
  1. @page "/"  
  2. <h4>Connecting Same Cosmos DB Database in Local Emulator using SQL API and Mongo API</h4>  
  3. <p>This is an experimental approach to connect same Cosmos DB database in a local emulator with SQL API and Mongo API </p>  
  4. <p>We are using Cosmos DB Local Emulator to create the database without any cost.</p>  

We have completed all the coding part. Let us run the application and verify the features.

 
We can add a new Employee now.
 
 
After saving the data, we can check the document in Emulator.
 
 
Please note our “EmployeeSQL” collection was created with current employee data.

We can now switch our application to Mongo API mode by simply changing the service in Startup class.

 

We can run the application and create one employee data again.

We can see that “EmployeeMongo” collection is also created with one document.
 
 
 
In Mongo API, we can see there is one additional $oid (ObjectId) created.

Please look at the below image to compare the different collection details.

 

Conclusion

In this article, we saw how to create a Blazor app in Visual Studio Community edition and created a single Cosmos DB account using different .NET SDKs. Then, we connected this database with the SQL API and MongoDB API. We created separate Collections for SQL API and Mongo API.

This is an experimental approach; if you like the article, please feel free to give feedback.


Similar Articles