How to Use Cosmos DB with .NET: Simple Guide
To use
Cosmos DB with .NET, install the Microsoft.Azure.Cosmos NuGet package and create a CosmosClient with your account endpoint and key. Then, use this client to access databases and containers for storing and querying JSON documents.Syntax
The main steps to use Cosmos DB with .NET are:
- Install SDK: Add
Microsoft.Azure.Cosmospackage. - Create Client: Initialize
CosmosClientwith endpoint URL and key. - Access Database: Use
GetDatabaseorCreateDatabaseIfNotExistsAsync. - Access Container: Use
GetContainerorCreateContainerIfNotExistsAsync. - CRUD Operations: Use container methods like
CreateItemAsync,ReadItemAsync,ReplaceItemAsync, andDeleteItemAsync.
csharp
using Microsoft.Azure.Cosmos; // Create a CosmosClient CosmosClient client = new CosmosClient("<your-endpoint>", "<your-key>"); // Get or create a database Database database = await client.CreateDatabaseIfNotExistsAsync("MyDatabase"); // Get or create a container Container container = await database.CreateContainerIfNotExistsAsync("MyContainer", "/partitionKey"); // Create an item await container.CreateItemAsync(new { id = "1", partitionKey = "pk1", name = "Item1" }, new PartitionKey("pk1"));
Example
This example shows how to connect to Cosmos DB, create a database and container, add an item, and read it back.
csharp
using System; using System.Threading.Tasks; using Microsoft.Azure.Cosmos; class Program { private static readonly string EndpointUri = "https://your-cosmos-account.documents.azure.com:443/"; private static readonly string PrimaryKey = "your-primary-key"; private CosmosClient cosmosClient; private Database database; private Container container; private string databaseId = "SampleDB"; private string containerId = "Items"; public static async Task Main(string[] args) { Program p = new Program(); await p.RunAsync(); } public async Task RunAsync() { cosmosClient = new CosmosClient(EndpointUri, PrimaryKey); database = await cosmosClient.CreateDatabaseIfNotExistsAsync(databaseId); container = await database.CreateContainerIfNotExistsAsync(containerId, "/category"); var newItem = new Item { Id = "1", Category = "Books", Name = "Azure Cosmos DB Guide" }; await container.CreateItemAsync(newItem, new PartitionKey(newItem.Category)); ItemResponse<Item> response = await container.ReadItemAsync<Item>("1", new PartitionKey("Books")); Console.WriteLine($"Read item: {response.Resource.Name} in category {response.Resource.Category}"); } } public class Item { public string Id { get; set; } public string Category { get; set; } public string Name { get; set; } }
Output
Read item: Azure Cosmos DB Guide in category Books
Common Pitfalls
Common mistakes when using Cosmos DB with .NET include:
- Not specifying the correct
PartitionKeywhen creating or reading items, causing errors. - Using synchronous methods instead of async, which can block your app.
- Hardcoding keys and endpoints instead of using secure configuration.
- Not handling exceptions like
CosmosExceptionfor retries or errors.
csharp
/* Wrong: Missing PartitionKey when creating item */ await container.CreateItemAsync(new { id = "2", name = "NoPartitionKey" }); /* Right: Include PartitionKey */ await container.CreateItemAsync(new { id = "2", partitionKey = "pk2", name = "WithPartitionKey" }, new PartitionKey("pk2"));
Quick Reference
Tips for using Cosmos DB with .NET:
- Always use
async/awaitfor Cosmos DB calls. - Store your endpoint and key securely (e.g., environment variables).
- Use partition keys to optimize performance and scalability.
- Handle exceptions to manage throttling and errors gracefully.
- Use the latest
Microsoft.Azure.CosmosSDK version for best features and support.
Key Takeaways
Install and use the Microsoft.Azure.Cosmos SDK to connect .NET apps to Cosmos DB.
Always specify the correct partition key when creating or querying items.
Use async methods to keep your app responsive and scalable.
Securely manage your Cosmos DB credentials outside your code.
Handle Cosmos DB exceptions to improve reliability and user experience.