Using Azure Cosmos DB with .NET Applications
Introduction to Azure Cosmos DB
Azure Cosmos DB is a globally distributed, multi-model database service designed to provide high availability, low latency, and scalability. In this tutorial, we'll explore how to use Azure Cosmos DB with .NET applications.
Prerequisites
Before you begin, ensure you have the following:
- An Azure account. You can sign up for a free account at azure.microsoft.com.
- Visual Studio installed on your machine.
- A .NET application ready for integration with Azure Cosmos DB.
Creating an Azure Cosmos DB Account
First, you need to create an Azure Cosmos DB account.
// Steps to create an Azure Cosmos DB account
// 1. Go to the Azure portal (https://portal.azure.com)
// 2. Click "Create a resource"
// 3. Select "Azure Cosmos DB"
// 4. Choose the API you want to use (e.g., SQL, MongoDB, Cassandra, etc.)
// 5. Fill in the required details such as Subscription, Resource group, Account name, and Location
// 6. Click "Review + create" and then "Create"
Installing Azure Cosmos DB NuGet Packages
Next, install the necessary NuGet packages for Azure Cosmos DB.
// Install the Microsoft.Azure.Cosmos package
// PM> Install-Package Microsoft.Azure.Cosmos
Connecting to Azure Cosmos DB
After installing the packages, connect your .NET application to Azure Cosmos DB.
// Connecting to Azure Cosmos DB
using Microsoft.Azure.Cosmos;
public class CosmosDbService
{
private readonly CosmosClient _cosmosClient;
private readonly Container _container;
public CosmosDbService(string account, string key, string databaseName, string containerName)
{
_cosmosClient = new CosmosClient(account, key);
var database = _cosmosClient.GetDatabase(databaseName);
_container = database.GetContainer(containerName);
}
}
Creating Items in Azure Cosmos DB
Let's create an item in Azure Cosmos DB.
// Creating an item in Azure Cosmos DB
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos;
public class CosmosDbService
{
private readonly Container _container;
public CosmosDbService(string account, string key, string databaseName, string containerName)
{
var cosmosClient = new CosmosClient(account, key);
var database = cosmosClient.GetDatabase(databaseName);
_container = database.GetContainer(containerName);
}
public async Task AddItemAsync(T item)
{
await _container.CreateItemAsync(item, new PartitionKey(typeof(T).GetProperty("Id").GetValue(item, null).ToString()));
}
}
// Usage
var cosmosDbService = new CosmosDbService("YourAccountEndpoint", "YourAccountKey", "YourDatabaseName", "YourContainerName");
await cosmosDbService.AddItemAsync(new { Id = "1", Name = "Item 1" });
Reading Items from Azure Cosmos DB
Next, read an item from Azure Cosmos DB.
// Reading an item from Azure Cosmos DB
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos;
public class CosmosDbService
{
private readonly Container _container;
public CosmosDbService(string account, string key, string databaseName, string containerName)
{
var cosmosClient = new CosmosClient(account, key);
var database = cosmosClient.GetDatabase(databaseName);
_container = database.GetContainer(containerName);
}
public async Task GetItemAsync(string id)
{
try
{
ItemResponse response = await _container.ReadItemAsync(id, new PartitionKey(id));
return response.Resource;
}
catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return default;
}
}
}
// Usage
var cosmosDbService = new CosmosDbService("YourAccountEndpoint", "YourAccountKey", "YourDatabaseName", "YourContainerName");
var item = await cosmosDbService.GetItemAsync<YourItemType>("1");
Querying Items in Azure Cosmos DB
You can also query items using SQL-like syntax.
// Querying items in Azure Cosmos DB
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos;
public class CosmosDbService
{
private readonly Container _container;
public CosmosDbService(string account, string key, string databaseName, string containerName)
{
var cosmosClient = new CosmosClient(account, key);
var database = cosmosClient.GetDatabase(databaseName);
_container = database.GetContainer(containerName);
}
public async Task> GetItemsAsync(string queryString)
{
var query = _container.GetItemQueryIterator(new QueryDefinition(queryString));
var results = new List();
while (query.HasMoreResults)
{
var response = await query.ReadNextAsync();
results.AddRange(response.ToList());
}
return results;
}
}
// Usage
var cosmosDbService = new CosmosDbService("YourAccountEndpoint", "YourAccountKey", "YourDatabaseName", "YourContainerName");
var items = await cosmosDbService.GetItemsAsync<YourItemType>("SELECT * FROM c WHERE c.Name = 'Item 1'");
Updating Items in Azure Cosmos DB
Let's update an item in Azure Cosmos DB.
// Updating an item in Azure Cosmos DB
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos;
public class CosmosDbService
{
private readonly Container _container;
public CosmosDbService(string account, string key, string databaseName, string containerName)
{
var cosmosClient = new CosmosClient(account, key);
var database = cosmosClient.GetDatabase(databaseName);
_container = database.GetContainer(containerName);
}
public async Task UpdateItemAsync(string id, T item)
{
await _container.UpsertItemAsync(item, new PartitionKey(id));
}
}
// Usage
var cosmosDbService = new CosmosDbService("YourAccountEndpoint", "YourAccountKey", "YourDatabaseName", "YourContainerName");
await cosmosDbService.UpdateItemAsync("1", new { Id = "1", Name = "Updated Item 1" });
Deleting Items from Azure Cosmos DB
Finally, delete an item from Azure Cosmos DB.
// Deleting an item from Azure Cosmos DB
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos;
public class CosmosDbService
{
private readonly Container _container;
public CosmosDbService(string account, string key, string databaseName, string containerName)
{
var cosmosClient = new CosmosClient(account, key);
var database = cosmosClient.GetDatabase(databaseName);
_container = database.GetContainer(containerName);
}
public async Task DeleteItemAsync(string id)
{
await _container.DeleteItemAsync<YourItemType>(id, new PartitionKey(id));
}
}
// Usage
var cosmosDbService = new CosmosDbService("YourAccountEndpoint", "YourAccountKey", "YourDatabaseName", "YourContainerName");
await cosmosDbService.DeleteItemAsync("1");
Conclusion
In this tutorial, we covered how to use Azure Cosmos DB with .NET applications. We discussed how to create a Cosmos DB account, connect to it, and perform CRUD operations. Azure Cosmos DB is a powerful database service that offers flexibility, scalability, and global distribution, making it a great choice for modern applications.