Azure Cosmos DB: Integration with .NET Core

DotNet Full Stack Dev
3 min readSep 24, 2024

--

Azure Cosmos DB is a globally distributed, multi-model database provided by Microsoft Azure. It allows developers to build highly responsive and scalable applications by offering low latency and high availability worldwide. This blog will provide a detailed look at Cosmos DB, exploring its core features, architecture, supported models, and use cases, while demonstrating how it can be integrated into .NET applications.

Embark on a journey of continuous learning and exploration with DotNet-FullStack-Dev. Uncover more by visiting our https://dotnet-fullstack-dev.blogspot.com reach out for further information.

What is Azure Cosmos DB?

Cosmos DB is designed as a globally distributed database that supports multiple data models, including key-value, document, column-family, and graph databases. It is ideal for applications requiring low-latency responses, large-scale data operations, and global reach with multiple regions.

Key Features of Cosmos DB

  1. Global Distribution: Cosmos DB automatically replicates data across multiple Azure regions, providing high availability, disaster recovery, and low-latency access.
  2. Multi-Model Support: Supports various APIs such as SQL (for document-based queries), MongoDB, Cassandra, Gremlin (for graph queries), and Azure Table API.
  3. Elastic Scalability: Offers horizontal scaling of storage and throughput, allowing the database to grow as needed without compromising performance.
  4. Guaranteed Low Latency: Cosmos DB provides low latency at the 99th percentile, making it highly efficient for real-time applications.
  5. Consistency Levels: Offers five consistency models: Strong, Bounded Staleness, Session, Consistent Prefix, and Eventual Consistency. This flexibility allows you to balance performance and consistency based on your application’s needs.

Let’s walk through the steps to integrate Cosmos DB into a .NET Core application using the SQL API (document model).

Step 1: Set Up Cosmos DB on Azure

Create Cosmos DB Account:

  • Go to the Azure Portal and create a new Azure Cosmos DB account.
  • Select the SQL API to use the document-based data model.

Create a Database and Container:

  • After creating the Cosmos DB account, add a new database and define a container (equivalent to a collection).
  • Select an appropriate partition key to ensure efficient data distribution.

Step 2: Set Up the .NET Core Project

Install the Cosmos SDK: Install the Azure Cosmos SDK for .NET Core by adding the NuGet package:

dotnet add package Microsoft.Azure.Cosmos

Configure Cosmos DB Client: In your application, configure the Cosmos DB client to connect to your Azure account.

using Microsoft.Azure.Cosmos;

public class CosmosDbService
{
private readonly CosmosClient _client;
private readonly Container _container;

public CosmosDbService(string endpointUri, string primaryKey, string databaseId, string containerId)
{
_client = new CosmosClient(endpointUri, primaryKey);
var database = _client.GetDatabase(databaseId);
_container = database.GetContainer(containerId);
}

// CRUD operations here
}

Step 3: Perform CRUD Operations

Here’s how you can perform CRUD operations on Cosmos DB using the .NET SDK.

1. Create an Item:

public async Task AddItemAsync(Item item)
{
await _container.CreateItemAsync(item, new PartitionKey(item.PartitionKey));
}

2. Read an Item:

public async Task<Item> GetItemAsync(string id, string partitionKey)
{
try
{
var response = await _container.ReadItemAsync<Item>(id, new PartitionKey(partitionKey));
return response.Resource;
}
catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
return null;
}
}

3. Update an Item:

public async Task UpdateItemAsync(string id, Item updatedItem)
{
await _container.UpsertItemAsync(updatedItem, new PartitionKey(updatedItem.PartitionKey));
}

4. Delete an Item:

public async Task DeleteItemAsync(string id, string partitionKey)
{
await _container.DeleteItemAsync<Item>(id, new PartitionKey(partitionKey));
}

Step 4: Running and Testing

  • Start your .NET Core application, ensuring your Cosmos DB client is properly configured.
  • Use Postman or a similar tool to test your API endpoints.

Use Cases of Cosmos DB

  1. Real-Time Analytics: Cosmos DB’s low-latency and global distribution make it ideal for real-time analytics applications, such as monitoring IoT devices or streaming data.
  2. E-Commerce Systems: Its ability to scale globally and handle high-throughput writes makes it a perfect fit for large-scale e-commerce platforms.
  3. Social Networks: With graph and document models, Cosmos DB can efficiently manage and query social network data, such as user profiles, posts, and relationships.

Conclusion

Azure Cosmos DB is a powerful, flexible, and globally distributed database service, offering multi-model capabilities, scalability, and high availability. Whether you’re working on real-time analytics, e-commerce platforms, or global applications, Cosmos DB can provide the infrastructure needed to ensure your data is available and responsive.

By integrating Cosmos DB with a .NET Core application, you can leverage its powerful SDKs to perform CRUD operations with ease. The step-by-step guide demonstrated how to build such an integration, providing you with the necessary knowledge to start using Cosmos DB in your next project.

--

--

DotNet Full Stack Dev
DotNet Full Stack Dev

Written by DotNet Full Stack Dev

Join me to master .NET Full Stack Development & boost your skills by 1% daily with insights, examples, and techniques! https://dotnet-fullstack-dev.blogspot.com

No responses yet