Introduction to SDK v4

The Azure Cosmos DB .NET SDK v4 is the latest generation of the official Microsoft SDK for interacting with Azure Cosmos DB from your C# applications. It is built upon the .NET Standard 2.0, making it compatible with a wide range of .NET platforms, including .NET Core, .NET Framework, and Mono.

This SDK offers enhanced performance, improved reliability, and a modern API design that simplifies common database operations. Whether you're building new cloud-native applications or modernizing existing ones, the v4 SDK is your gateway to leveraging the full power of Azure Cosmos DB.

Getting Started

Getting started with the .NET SDK v4 is straightforward. You'll need an Azure subscription and an existing Azure Cosmos DB account.

  1. Install the NuGet package:
    dotnet add package Microsoft.Azure.Cosmos
  2. Create a CosmosClient instance: You need your Cosmos DB endpoint and primary key.
    using Azure.Cosmos;

    string cosmosEndpoint = "YOUR_COSMOS_ENDPOINT";
    string cosmosPrimaryKey = "YOUR_COSMOS_PRIMARY_KEY";

    CosmosClient client = new CosmosClient(cosmosEndpoint, cosmosPrimaryKey);
  3. Access a database and container:
    string databaseId = "myDatabase";
    string containerId = "myContainer";

    Database database = await client.CreateDatabaseIfNotExistsAsync(databaseId);
    Container container = await database.CreateContainerIfNotExistsAsync(containerId, "/partitionKey");

You can find your endpoint and primary key in the Azure portal under your Cosmos DB account's "Keys" section.

View Full Quick Start Guide

Core Concepts

  • CosmosClient: The entry point for all Cosmos DB operations. It's recommended to create a single instance and reuse it throughout your application's lifetime.
  • Database: A logical namespace for containers.
  • Container: The core data structure, analogous to a table in relational databases or a collection in NoSQL databases. It holds items.
  • Item: A JSON document stored within a container.
  • Partition Key: A property within your items that determines how data is distributed across physical partitions for scalability and performance.

Usage Examples

Creating an Item

public class Product {
public string Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public int Price { get; set; }
public string PartitionKey { get; set; } // Matches the container's partition key definition
}

// Assuming 'container' is an initialized CosmosContainer object
Product newItem = new Product { Id = "product1", Name = "Laptop", Category = "Electronics", Price = 1200, PartitionKey = "Electronics" };
ItemResponse<Product> createResponse = await container.CreateItemAsync(newItem, new PartitionKey(newItem.PartitionKey));
Console.WriteLine($"Created item with id: {createResponse.Resource.Id}");

Reading an Item

string itemId = "product1";
string partitionKeyValue = "Electronics";

ItemResponse<Product> readResponse = await container.ReadItemAsync<Product>(itemId, new PartitionKey(partitionKeyValue));
Console.WriteLine($"Read item: {readResponse.Resource.Name}");

Querying Items

var query = container.GetItemLinqQuery<Product>()
.Where(p => p.Category == "Electronics" && p.Price > 1000)
.ToFeedIterator();

while (query.HasMoreResults) {
FeedResponse<Product> response = await query.ReadNextAsync();
foreach (var product in response) {
Console.WriteLine($"- {product.Name}");
}
}

Advanced Features

  • Change Feed: Process real-time data changes.
  • Transactions: Implement ACID transactions across multiple items within a logical partition.
  • Stored Procedures & UDFs: Execute logic directly on the server.
  • Indexing Policies: Customize indexing for optimal query performance.
  • Throughput Provisioning: Manage request units (RUs) for performance and cost control.
  • Multi-region Writes & Failover: Ensure global availability and resilience.

Best Practices

  • Singleton CosmosClient: Initialize and reuse the CosmosClient instance for efficiency.
  • Appropriate Partition Key: Design your partition key strategy carefully for optimal scalability and performance.
  • Batch Operations: Use batching for creating/upserting multiple items to reduce network latency and improve throughput.
  • Error Handling: Implement robust error handling, especially for transient network issues (retries).
  • Request Unit (RU) Awareness: Monitor and understand your RU consumption to optimize costs and performance.

Troubleshooting

Common issues include exceeding throughput limits (429 Too Many Requests), incorrect partition key usage, and network connectivity problems. The SDK provides detailed exceptions that can help diagnose these issues.

Check the official documentation for in-depth guides and troubleshooting tips.

Explore the Official Documentation