Mastering Azure Cosmos DB with ASP.NET Core

Introduction to Azure Cosmos DB

Azure Cosmos DB is a globally distributed, multi-model database service provided by Microsoft Azure. It is designed to offer turnkey global distribution across any number of Azure regions by transparently scaling and replicating your data wherever your users are. Cosmos DB ensures that your data is always available and allows you to elastically and independently scale throughput and storage across any number of Azure regions worldwide.

Key Features of Azure Cosmos DB

  1. Global Distribution: Distribute your data globally to any Azure region with a few clicks.
  2. Elastic Scalability: Independently and elastically scale throughput and storage across multiple regions.
  3. Multi-Model and Multi-API Support: Supports multiple data models such as document, key-value, graph, and column-family data models. APIs include SQL, MongoDB, Cassandra, Tables, and Gremlin.
  4. Guaranteed Low Latency: Provides single-digit millisecond response times.
  5. Comprehensive SLAs: Offers five well-defined consistency levels and 99.999% high availability.
  6. Automatic Indexing: Automatically indexes all data without requiring schema and index management.
  7. Security: Provides advanced security features, including encryption at rest, and compliance with major standards like GDPR and ISO.

Pros of Azure Cosmos DB

  1. Global Distribution: Easily replicate data across multiple regions, providing high availability and disaster recovery.
  2. Scalability: Effortlessly scale up or down based on your needs without downtime.
  3. Multiple Data Models: Flexibility to use different data models and APIs based on the application requirements.
  4. Performance: High throughput and low latency, making it suitable for mission-critical applications.
  5. Fully Managed: No need to manage infrastructure, allowing developers to focus on application development.
  6. Automatic Indexing: Simplifies data management by automatically indexing all data.
  7. Consistency Levels: Provides a spectrum of consistency levels from strong to eventual, allowing fine-grained control over consistency and performance.

Cons of Azure Cosmos DB

  1. Cost: This can be expensive, especially for large-scale operations or when using global distribution.
  2. Complexity: Learning curve associated with its various features and APIs.
  3. Vendor Lock-In: Tightly integrated with Azure, making it challenging to switch to other providers.
  4. Limited Open Source Support: Less community support compared to open-source alternatives.
  5. Provisioning Throughput: Requires careful planning of throughput units to avoid over-provisioning and under-provisioning.

Different Available Models

Azure Cosmos DB supports multiple data models, allowing developers to choose the best fit for their applications:

  1. Document Model: Store and query JSON documents. Ideal for applications requiring flexible schema and hierarchical data structures.

    • API: SQL, MongoDB
  2. Key-Value Model: Store simple key-value pairs. Suitable for applications requiring fast lookups.

    • API: Table
  3. Column-Family Model: Store data in rows and columns, similar to NoSQL databases like Cassandra. Best for write-heavy workloads.

    • API: Cassandra
  4. Graph Model: Store and query graph data structures, making it ideal for applications involving complex relationships.

    • API: Gremlin

Integration with ASP.NET Core MVC

Integrating Azure Cosmos DB with an ASP.NET Core MVC application involves the following steps:

1. Setting Up Azure Cosmos DB

  1. Create an Azure Cosmos DB Account: Go to the Azure portal, create a new Azure Cosmos DB account, choose the desired API, and set up the necessary configurations.
  2. Get Connection String: Retrieve the connection string and keys from the Azure portal for use in your application.

2. Configuring ASP.NET Core MVC Project

  • Install NuGet Packages: Install the necessary NuGet packages for Azure Cosmos DB in your ASP.NET Core MVC project.

    dotnet add package Microsoft.Azure.Cosmos
    
  • Add Configuration: Add the Cosmos DB configuration settings to your appsettings.json.

{
    "CosmosDb": {
        "Account": "<your-account-url>",
        "Key": "<your-account-key>",
        "DatabaseName": "YourDatabaseName",
        "ContainerName": "YourContainerName"
    }
}
  • Configure Services: Configure the Cosmos DB client in the Startup.cs file.

builder.Services.AddSingleton<CosmosClient>(serviceProvider =>
{
    var configuration = serviceProvider.GetRequiredService<IConfiguration>();
    var account = configuration["AzureCosmosDb:Account"];
    var key = configuration["AzureCosmosDb:Key"];

    return new CosmosClient(account, key);
});

3. Creating Data Models and Repositories

  • Define Data Models: Create C# classes that represent your data models.
public record Student(
        string id,
        string name,
        string email,
        List<string> hobbies
        );
  • Create Repository: Implement a repository pattern to interact with Cosmos DB.
public class StudentService
{
    private readonly Container _container;
    public StudentService(IConfiguration configuration,CosmosClient cosmosClient)
    {
        var databaseName = configuration["AzureCosmosDb:DatabaseName"];
        var containerName = configuration["AzureCosmosDb:ContainerName"];

        _container = cosmosClient.GetContainer(databaseName, containerName);
    }
    public async Task Insert(Student model)
    {
        await _container.CreateItemAsync(model);
    }
    public async Task<IEnumerable<Student>> GetAll()
    {
        var respones = _container.GetItemLinqQueryable<Student>(true);
        return respones.AsEnumerable();
    }
    public async Task<Student> Get(string id)
    {
        return await _container.ReadItemAsync<Student>(id,PartitionKey.None);
    }
    public async Task Delete(string id)
    {
        await _container.DeleteItemAsync<Student>(id,PartitionKey.None);
    }
}

4. Using the Repository in Controllers

  • Inject Repository: Inject the repository into your controllers and use it to perform CRUD operations.
[Route("api/[controller]")]
[ApiController]
public class StudentsController(StudentService studentService) : ControllerBase
{
    [HttpGet("GetAll")]
    public async Task<IActionResult> GetAll()
    {
        var response = await studentService.GetAll();
        return Ok(response);
    }
    [HttpGet("Get")]
    public async Task<IActionResult> Get(string id)
    {
        var response = await studentService.Get(id);
        return Ok(response);
    }
    [HttpPut("Insert")]
    public async Task<IActionResult> Insert(Student request)
    {
        await studentService.Insert(request);
        return Ok("Student created successfully");
    }
    [HttpDelete("Delete")]
    public async Task<IActionResult> Delete(string id)
    {
        await studentService.Delete(id);
        return Ok("Student delete successfully");
    }
}

By following these steps, you can integrate Azure Cosmos DB with your ASP.NET Core MVC application, enabling you to leverage the powerful capabilities of Cosmos DB for your web applications.

Conclusion

Azure Cosmos DB is a robust and flexible database service that offers global distribution, high availability, and multi-model support. While it comes with some complexity and cost considerations, its benefits for large-scale, globally distributed applications are significant. Integrating it with an ASP.NET Core MVC application is straightforward, allowing developers to build scalable and responsive applications with ease.

Source Code

You can access the code from my AzureEssentialSeries Github Repo. Please give it a start if you like it.

Video Tutorial

You can watch the Azure Essentials show Episode 2 on CSharpTV for this topic.


Similar Articles
Finchship
We Provide Web, Desktop and Mobile Apps Solution