Azure Cosmos DB .NET SDK

This tutorial guides you through the essential steps of using the Azure Cosmos DB .NET SDK to interact with your NoSQL data. We'll cover creating resources, performing CRUD operations, and querying data.

Prerequisites

1. Install the NuGet Package

First, you need to add the Azure Cosmos DB .NET SDK to your project. Open your project in Visual Studio or use the .NET CLI and run the following command:

dotnet add package Microsoft.Azure.Cosmos

2. Initialize the Cosmos DB Client

To connect to your Cosmos DB account, you need to initialize the CosmosClient. You'll need your account's endpoint and primary key, which can be found in the Azure portal.

using Microsoft.Azure.Cosmos; // Your Cosmos DB endpoint and key string endpoint = "YOUR_COSMOS_DB_ENDPOINT"; string key = "YOUR_COSMOS_DB_PRIMARY_KEY"; // Initialize the Cosmos client CosmosClient client = new CosmosClient(endpoint, key);
Note: It's recommended to store your endpoint and key securely, for example, using Azure Key Vault or application configuration settings, rather than hardcoding them.

3. Create a Database and Container

Next, you'll create a database and a container within that database. A container is where your data is stored.

// Reference to the database Database database = await client.CreateDatabaseIfNotExistsAsync("ToDoList"); // Reference to the container Container container = await database.CreateContainerIfNotExistsAsync("Items", "/category"); // The "/category" is the partition key path. Choose a property that distributes your data evenly.

4. Create an Item (Document)

Now, let's add some data to your container. Items in Cosmos DB are typically JSON documents.

First, define a C# class to represent your item:

public class TodoItem { public string id { get; set; } public string description { get; set; } public string category { get; set; } public bool isComplete { get; set; } }

Then, create and add the item:

TodoItem newItem = new TodoItem { id = Guid.NewGuid().ToString(), // Unique identifier for the item description = "Buy groceries", category = "Personal", isComplete = false }; ItemResponse response = await container.CreateItemAsync(newItem, new PartitionKey(newItem.category)); Console.WriteLine($"Created item with id: {response.Resource.id}");

5. Read an Item

You can retrieve a specific item using its ID and partition key.

string itemId = "YOUR_ITEM_ID"; // Replace with the actual ID of the item you want to read string itemCategory = "Personal"; // Replace with the actual category ItemResponse readResponse = await container.ReadItemAsync(itemId, new PartitionKey(itemCategory)); TodoItem retrievedItem = readResponse.Resource; Console.WriteLine($"Retrieved item: {retrievedItem.description}");

6. Update an Item

To update an item, you can use the UpsertItemAsync method. If the item exists, it will be updated; otherwise, it will be created.

// Assume 'retrievedItem' is the item fetched in the previous step retrievedItem.isComplete = true; ItemResponse updateResponse = await container.UpsertItemAsync(retrievedItem, new PartitionKey(retrievedItem.category)); Console.WriteLine($"Updated item with id: {updateResponse.Resource.id}. Is Complete: {updateResponse.Resource.isComplete}");

7. Delete an Item

Delete an item using its ID and partition key.

string itemIdToDelete = "YOUR_ITEM_ID"; // Replace with the ID of the item to delete string itemCategoryToDelete = "Personal"; // Replace with the category await container.DeleteItemAsync(itemIdToDelete, new PartitionKey(itemCategoryToDelete)); Console.WriteLine($"Deleted item with id: {itemIdToDelete}");

8. Query Items

Cosmos DB supports rich querying using SQL. You can use the GetItemQueryIterator method.

string queryText = "SELECT * FROM c WHERE c.isComplete = false"; QueryDefinition queryDefinition = new QueryDefinition(queryText); FeedIterator queryIterator = container.GetItemQueryIterator(queryDefinition); while (queryIterator.HasMoreResults) { FeedResponse response = await queryIterator.ReadNextAsync(); foreach (TodoItem item in response) { Console.WriteLine($"Incomplete item: {item.description}"); } }
Tip: Explore more advanced SQL queries for filtering, sorting, and aggregation. Refer to the Cosmos DB SQL Query documentation.

Next Steps