π Azure Cosmos DB for .NET — Beginner’s Guide
If you’re a .NET developer and hearing about Azure Cosmos DB for the first time, think of it like this:
π Imagine a super-powered cloud database that:
- Automatically scales to handle millions of users.
- Lets you store data as JSON documents instead of fixed tables.
- Works globally with very fast response times.
- Doesn’t need you to manage servers, storage, or upgrades.
Cosmos DB = a NoSQL database that plays really well with .NET.
π Core Concepts (Simple Terms)
- Database Account → Think of it as your big box in Azure that holds everything.
- Database → Like a folder inside the box.
- Container → Like a table (but more flexible). You put your data here.
- Item → One JSON document (like a row in SQL, but JSON).
- Partition Key → A way to tell Cosmos how to spread your data across multiple storage units so it can scale.
π Example: If you’re storing Orders, you might use CustomerId as partition key. This way, all orders for a customer are stored together.
⚡ Step 1: Set up Cosmos DB
- Go to the Azure Portal.
- Search for Cosmos DB → Create → Choose Core (SQL) API.
(Don’t worry, it supports MongoDB, Graph, Cassandra, etc., but SQL API is easiest for beginners). - Get your Endpoint and Key (Azure gives you these to connect from your app).
⚡ Step 2: Install the .NET SDK
Open your terminal in your project folder and run:
dotnet add package Azure.Cosmos
⚡ Step 3: Write Your First .NET Code
Here’s a beginner-friendly C# example with comments:
using Azure.Cosmos;
using System;
using System.Threading.Tasks;
public class Program
{
// These come from your Azure Cosmos DB account
private static readonly string endpoint = "<COSMOS_ENDPOINT>";
private static readonly string key = "<COSMOS_KEY>";
private static readonly string databaseId = "SampleDatabase";
private static readonly string containerId = "Products";
public static async Task Main()
{
// Step 1: Create a CosmosClient
CosmosClient client = new CosmosClient(endpoint, key);
// Step 2: Create Database if it doesn’t exist
CosmosDatabase database = await client.CreateDatabaseIfNotExistsAsync(databaseId);
// Step 3: Create Container with partition key "/category"
CosmosContainer container = await database.CreateContainerIfNotExistsAsync(
containerId,
partitionKeyPath: "/category", // Partition key
throughput: 400 // Minimum RU/s (Request Units)
);
// Step 4: Create an item (JSON document)
var product = new
{
id = Guid.NewGuid().ToString(), // every item must have an "id"
category = "electronics",
name = "Laptop",
price = 750
};
// Insert the item
await container.CreateItemAsync(product, new PartitionKey(product.category));
Console.WriteLine("✅ Item inserted successfully!");
}
}
π What this does:
- Connects to Cosmos DB
- Creates a database and a container if they don’t exist
- Adds one item (document) to the container
⚡ Step 4: Read Data Back
Add this after the insert code:
// Read item back using id and partition key
var response = await container.ReadItemAsync<dynamic>(product.id, new PartitionKey(product.category));
Console.WriteLine($"π¦ Retrieved item: {response.Resource.name}, Price: {response.Resource.price}");
⚡ Step 5: Query Like SQL
Cosmos DB lets you query with SQL-like syntax:
var query = "SELECT * FROM c WHERE c.price > 500";
var iterator = container.GetItemQueryIterator<dynamic>(query);
while (iterator.HasMoreResults)
{
foreach (var item in await iterator.ReadNextAsync())
{
Console.WriteLine($"Found item: {item.name} with price {item.price}");
}
}
π Why Beginners Love Cosmos DB
- No Schema Headache → Store JSON directly, no need for table migrations.
- Global Scale → Your app can serve users across continents.
- Flexible Consistency → You decide: strong (always correct) or eventual (faster, cheaper).
- Pay for What You Use → RU/s system means you pay for requests, not fixed server costs.
⚠️ Common Beginner Mistakes
- Bad partition key → Always choose something that spreads data evenly (not just "true/false").
- Using
SELECT *→ Fetch only what you need to save cost. - Ignoring RU/s → Monitor RU usage or you’ll hit limits.
✅ Summary
You just:
✔ Learned Cosmos DB basics (Account, Database, Container, Items, Partition Key)
✔ Connected to Cosmos DB with .NET SDK
✔ Inserted, Read, and Queried data
Cosmos DB is powerful but beginner-friendly once you understand these basics. Start small, then explore advanced features like Change Feed (real-time event streaming) and Transactional Batch (mini-transactions inside one partition).
Comments
Post a Comment