Azure Cosmos DB .NET SDK v4

This document provides a comprehensive guide to using the latest version of the Azure Cosmos DB .NET SDK (v4). This SDK offers a robust and efficient way to interact with your Cosmos DB accounts from your .NET applications.

Key Features of v4 SDK

Getting Started

1. Installation

You can install the Azure Cosmos DB .NET SDK via NuGet Package Manager:

dotnet add package Microsoft.Azure.Cosmos

2. Initialize the Cosmos Client

The CosmosClient is the entry point for all Cosmos DB operations. You'll need your Cosmos DB account endpoint and primary key.

using Microsoft.Azure.Cosmos;

// Replace with your actual endpoint and key
string endpoint = "https://your-cosmos-db-account.documents.azure.com:443/";
string key = "YOUR_PRIMARY_KEY";

CosmosClient client = new CosmosClient(endpoint, key);

Core Concepts

Databases and Containers

Azure Cosmos DB organizes data into databases and containers. A container can hold a collection of items (documents, rows, graphs, etc.).

Creating a Database

// Create a new database if it doesn't exist
Database database = await client.CreateDatabaseIfNotExistsAsync("myDatabase");
Console.WriteLine($"Database created: {database.Id}");

Creating a Container

When creating a container, you need to specify the partition key path. This is crucial for performance and scalability.

// Create a new container if it doesn't exist
Container container = await database.CreateContainerIfNotExistsAsync(
    "myContainer",
    "/partitionKey", // e.g., "/category" or "/userId"
    400 // Request Units per second (RU/s)
);
Console.WriteLine($"Container created: {container.Id}");

CRUD Operations

Creating an Item

Items are typically JSON documents. You can define a C# class to map to your JSON structure.

public class ToDoItem
{
    public string id { get; set; } // Must be unique within the container
    public string category { get; set; }
    public string task { get; set; }
    public bool isComplete { get; set; }
    public string partitionKey { get; set; } // Must match the container's partition key
}

// Example item
ToDoItem item = new ToDoItem
{
    id = Guid.NewGuid().ToString(),
    category = "Personal",
    task = "Buy groceries",
    isComplete = false,
    partitionKey = "Personal" // Value for the partition key defined for the container
};

// Create the item
ItemResponse response = await container.CreateItemAsync(item, new PartitionKey(item.partitionKey));
Console.WriteLine($"Created item with ID: {response.Resource.id} and RU consumed: {response.RequestCharge}");

Reading an Item

Retrieve an item using its ID and partition key.

// Get the item by its ID and partition key
string itemId = response.Resource.id;
string itemPartitionKey = item.partitionKey;

response = await container.ReadItemAsync(itemId, new PartitionKey(itemPartitionKey));
ToDoItem retrievedItem = response.Resource;
Console.WriteLine($"Retrieved item: {retrievedItem.task}");

Updating an Item

You can update an existing item. The entire item needs to be sent in the request.

// Update the item
retrievedItem.isComplete = true;
retrievedItem.task = "Buy organic groceries";

response = await container.ReplaceItemAsync(retrievedItem.id, retrievedItem, new PartitionKey(retrievedItem.partitionKey));
Console.WriteLine($"Updated item with ID: {response.Resource.id}");

Deleting an Item

Delete an item using its ID and partition key.

// Delete the item
response = await container.DeleteItemAsync(itemId, new PartitionKey(itemPartitionKey));
Console.WriteLine($"Deleted item with ID: {response.Resource.id}");

Querying Data

Use SQL-like queries to retrieve data. The SDK provides methods for executing queries.

IOrderedQueryable queryable = container.GetItemLinqQueryable()
                .Where(item => item.category == "Personal" && !item.isComplete);

FeedIterator feedIterator = queryable.ToFeedIterator();

Console.WriteLine("Tasks in 'Personal' category that are not complete:");
while (feedIterator.HasMoreResults)
{
    FeedResponse response = await feedIterator.ReadNextAsync();
    foreach (ToDoItem item in response)
    {
        Console.WriteLine($" - {item.task}");
    }
}

Further Reading