NoSQL databases offer a flexible and scalable solution for modern applications that need to handle large amounts of unstructured data. In this blog post, we’ll focus on using Azure Cosmos DB for NoSQL with .NET 8. We’ll go through examples of loading, inserting, and updating data, and highlight important aspects to consider in this context.
Prerequisites
Before we start, make sure you have the following prerequisites:
- An Azure account with an active subscription.
- .NET 8 SDK installed.
- Azure Cosmos DB for NoSQL account created.
Setting Up the Project
First, create a new .NET 8 project and add the necessary NuGet packages:
dotnet new console -n CosmosDBExample
cd CosmosDBExample
dotnet add package Microsoft.Azure.Cosmos
Connecting to Cosmos DB
Create a connection to your Cosmos DB instance:
using Microsoft.Azure.Cosmos;
string endpointUri = "https://<your-cosmos-db-account>.documents.azure.com:443/";
string primaryKey = "<your-primary-key>";
CosmosClient cosmosClient = new CosmosClient(endpointUri, primaryKey);
Creating Database and Container
Create a database and a container if they do not already exist:
Database database = await cosmosClient.CreateDatabaseIfNotExistsAsync("ExampleDatabase");
Container container = await database.CreateContainerIfNotExistsAsync("ExampleContainer", "/partitionKey");
Inserting Data
Insert a new document into the container:
public class Item
{
public string Id { get; set; }
public string PartitionKey { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
}
Item newItem = new Item
{
Id = Guid.NewGuid().ToString(),
PartitionKey = "examplePartition",
Name = "Example Item",
Quantity = 10
};
Item createdItem = await container.CreateItemAsync(newItem, new PartitionKey(newItem.PartitionKey));
Querying Data
Load data from the container:
string sqlQueryText = "SELECT * FROM c WHERE c.PartitionKey = 'examplePartition'";
QueryDefinition queryDefinition = new QueryDefinition(sqlQueryText);
FeedIterator<Item> queryResultSetIterator = container.GetItemQueryIterator<Item>(queryDefinition);
List<Item> items = new List<Item>();
while (queryResultSetIterator.HasMoreResults)
{
FeedResponse<Item> currentResultSet = await queryResultSetIterator.ReadNextAsync();
foreach (Item item in currentResultSet)
{
items.Add(item);
}
}
Updating Data
Update an existing document:
Item itemToUpdate = items.First();
itemToUpdate.Quantity = 20;
Item updatedItem = await container.ReplaceItemAsync(itemToUpdate, itemToUpdate.Id, new PartitionKey(itemToUpdate.PartitionKey));
Important Aspects
- Partitioning: Ensure your data is partitioned sensibly to optimize performance.
- Consistency Models: Choose the right consistency model (e.g., Eventual Consistency, Strong Consistency) based on your application’s requirements.
- Cost Management: Monitor costs, as Cosmos DB is billed based on throughput (RU/s).
Summary
In this blog post, we’ve covered the basics of working with Azure Cosmos DB for NoSQL in .NET 8. We’ve seen how to connect, insert, query, and update data. By paying attention to partitioning, consistency models, and cost management, you can make your application efficient and cost-effective.
Here are some useful links for futher reading:
: Azure Cosmos DB for NoSQL .NET Samples
: Quickstart: .NET Client Library – Azure Cosmos DB for NoSQL