Quickstart: Azure Cosmos DB SQL API client library for .NET
APPLIES TO:
SQL API
Get started with the Azure Cosmos DB client library for .NET to create databases, containers, and items within your account. Without a credit card or an Azure subscription, you can set up a free Try Azure Cosmos DB account. Follow these steps to install the package and try out example code for basic tasks.
Note
The example code snippets are available on GitHub as a .NET project.
API reference documentation | Library source code | Package (NuGet) | Samples
Prerequisites
- An Azure account with an active subscription. Create an account for free.
- .NET 6.0 or later
- Azure Command-Line Interface (CLI) or Azure PowerShell
Prerequisite check
- In a terminal or command window, run
dotnet --versionto check that the .NET SDK is version 6.0 or later. - Run
az --version(Azure CLI) orGet-Module -ListAvailable AzureRM(Azure PowerShell) to check that you have the appropriate Azure command-line tools installed.
Setting up
This section walks you through creating an Azure Cosmos account and setting up a project that uses Azure Cosmos DB SQL API client library for .NET to manage resources.
Create an Azure Cosmos DB account
This quickstart will create a single Azure Cosmos DB account using the SQL API.
Create shell variables for accountName, resourceGroupName, and location.
# Variable for resource group name resourceGroupName="msdocs-cosmos-quickstart-rg" location="westus" # Variable for account name with a randomnly generated suffix let suffix=$RANDOM*$RANDOM accountName="msdocs-$suffix"If you haven't already, sign in to the Azure CLI using the
az logincommand.Use the
az group createcommand to create a new resource group in your subscription.az group create \ --name $resourceGroupName \ --location $locationUse the
az cosmosdb createcommand to create a new Azure Cosmos DB SQL API account with default settings.az cosmosdb create \ --resource-group $resourceGroupName \ --name $accountName \ --locations regionName=$locationGet the SQL API endpoint URI for the account using the
az cosmosdb showcommand.az cosmosdb show \ --resource-group $resourceGroupName \ --name $accountName \ --query "documentEndpoint"Find the PRIMARY KEY from the list of keys for the account with the
az-cosmosdb-keys-listcommand.az cosmosdb keys list \ --resource-group $resourceGroupName \ --name $accountName \ --type "keys" \ --query "primaryMasterKey"Record the URI and PRIMARY KEY values. You'll use these credentials later.
Create a new .NET app
Create a new .NET application in an empty folder using your preferred terminal. Use the dotnet new command specifying the console template.
dotnet new console
Install the package
Add the Microsoft.Azure.Cosmos NuGet package to the .NET project. Use the dotnet add package command specifying the name of the NuGet package.
dotnet add package Microsoft.Azure.Cosmos
Build the project with the dotnet build command.
dotnet build
Make sure that the build was successful with no errors. The expected output from the build should look something like this:
Determining projects to restore...
All projects are up-to-date for restore.
dslkajfjlksd -> C:\Users\sidandrews\Demos\dslkajfjlksd\bin\Debug\net6.0\dslkajfjlksd.dll
Build succeeded.
0 Warning(s)
0 Error(s)
Configure environment variables
To use the URI and PRIMARY KEY values within your .NET code, persist them to new environment variables on the local machine running the application. To set the environment variable, use your preferred terminal to run the following commands:
$env:COSMOS_ENDPOINT = "<cosmos-account-URI>"
$env:COSMOS_KEY = "<cosmos-account-PRIMARY-KEY>"
Object model
Before you start building the application, let's look into the hierarchy of resources in Azure Cosmos DB. Azure Cosmos DB has a specific object model used to create and access resources. The Azure Cosmos DB creates resources in a hierarchy that consists of accounts, databases, containers, and items.
Hierarchical diagram showing an Azure Cosmos DB account at the top. The account has two child database nodes. One of the database nodes includes two child container nodes. The other database node includes a single child container node. That single container node has three child item nodes.
For more information about the hierarchy of different resources, see working with databases, containers, and items in Azure Cosmos DB.
You'll use the following .NET classes to interact with these resources:
CosmosClient- This class provides a client-side logical representation for the Azure Cosmos DB service. The client object is used to configure and execute requests against the service.Database- This class is a reference to a database that may, or may not, exist in the service yet. The database is validated server-side when you attempt to access it or perform an operation against it.Container- This class is a reference to a container that also may not exist in the service yet. The container is validated server-side when you attempt to work with it.QueryDefinition- This class represents a SQL query and any query parameters.FeedIterator<>- This class represents an iterator that can track the current page of results and get a new page of results.FeedResponse<>- This class represents a single page of responses from the iterator. This type can be iterated over using aforeachloop.
Code examples
The sample code described in this article creates a database named adventureworks with a container named products. The products table is designed to contain product details such as name, category, quantity, and a sale indicator. Each product also contains a unique identifier.
For this sample code, the container will use the category as a logical partition key.
Authenticate the client
From the project directory, open the Program.cs file. In your editor, add a using directive for Microsoft.Azure.Cosmos.
using Microsoft.Azure.Cosmos;
Define a new instance of the CosmosClient class using the constructor, and Environment.GetEnvironmentVariable to read the two environment variables you created earlier.
// New instance of CosmosClient class
using CosmosClient client = new(
accountEndpoint: Environment.GetEnvironmentVariable("COSMOS_ENDPOINT")!,
authKeyOrResourceToken: Environment.GetEnvironmentVariable("COSMOS_KEY")!
);
For more information on different ways to create a CosmosClient instance, see Get started with Azure Cosmos DB SQL API and .NET.
Create a database
Use the CosmosClient.CreateDatabaseIfNotExistsAsync method to create a new database if it doesn't already exist. This method will return a reference to the existing or newly created database.
// Database reference with creation if it does not already exist
Database database = await client.CreateDatabaseIfNotExistsAsync(
id: "adventureworks"
);
Console.WriteLine($"New database:\t{database.Id}");
For more information on creating a database, see Create a database in Azure Cosmos DB SQL API using .NET.
Create a container
The Database.CreateContainerIfNotExistsAsync will create a new container if it doesn't already exist. This method will also return a reference to the container.
// Container reference with creation if it does not alredy exist
Container container = await database.CreateContainerIfNotExistsAsync(
id: "products",
partitionKeyPath: "/category",
throughput: 400
);
Console.WriteLine($"New container:\t{container.Id}");
For more information on creating a container, see Create a container in Azure Cosmos DB SQL API using .NET.
Create an item
The easiest way to create a new item in a container is to first build a C# class or record type with all of the members you want to serialize into JSON. In this example, the C# record has a unique identifier, a category field for the partition key, and extra name, quantity, and sale fields.
// C# record representing an item in the container
public record Product(
string id,
string category,
string name,
int quantity,
bool sale
);
Create an item in the container by calling Container.UpsertItemAsync. In this example, we chose to upsert instead of create a new item in case you run this sample code more than once.
// Create new object and upsert (create or replace) to container
Product newItem = new(
id: "68719518391",
category: "gear-surf-surfboards",
name: "Yamba Surfboard",
quantity: 12,
sale: false
);
Product createdItem = await container.UpsertItemAsync<Product>(
item: newItem,
partitionKey: new PartitionKey("gear-surf-surfboards")
);
Console.WriteLine($"Created item:\t{createdItem.id}\t[{createdItem.category}]");
For more information on creating, upserting, or replacing items, see Create an item in Azure Cosmos DB SQL API using .NET.
Get an item
In Azure Cosmos DB, you can perform a point read operation by using both the unique identifier (id) and partition key fields. In the SDK, call Container.ReadItemAsync<> passing in both values to return a deserialized instance of your C# type.
// Point read item from container using the id and partitionKey
Product readItem = await container.ReadItemAsync<Product>(
id: "68719518391",
partitionKey: new PartitionKey("gear-surf-surfboards")
);
For more information about reading items and parsing the response, see Read an item in Azure Cosmos DB SQL API using .NET.
Query items
After you insert an item, you can run a query to get all items that match a specific filter. This example runs the SQL query: SELECT * FROM todo t WHERE t.partitionKey = 'gear-surf-surfboards'. This example uses the QueryDefinition type and a parameterized query expression for the partition key filter. Once the query is defined, call Container.GetItemQueryIterator<> to get a result iterator that will manage the pages of results. Then, use a combination of while and foreach loops to retrieve pages of results and then iterate over the individual items.
// Create query using a SQL string and parameters
var query = new QueryDefinition(
query: "SELECT * FROM products p WHERE p.category = @key"
)
.WithParameter("@key", "gear-surf-surfboards");
using FeedIterator<Product> feed = container.GetItemQueryIterator<Product>(
queryDefinition: query
);
while (feed.HasMoreResults)
{
FeedResponse<Product> response = await feed.ReadNextAsync();
foreach (Product item in response)
{
Console.WriteLine($"Found item:\t{item.name}");
}
}
Run the code
This app creates an Azure Cosmos DB SQL API database and container. The example then creates an item and then reads the exact same item back. Finally, the example issues a query that should only return that single item. With each step, the example outputs metadata to the console about the steps it has performed.
To run the app, use a terminal to navigate to the application directory and run the application.
dotnet run
The output of the app should be similar to this example:
New database: adventureworks
New container: products
Created item: 68719518391 [gear-surf-surfboards]
Clean up resources
When you no longer need the Azure Cosmos DB SQL API account, you can delete the corresponding resource group.
Use the az group delete command to delete the resource group.
az group delete --name $resourceGroupName
Next steps
In this quickstart, you learned how to create an Azure Cosmos DB SQL API account, create a database, and create a container using the .NET SDK. You can now dive deeper into the SDK to import more data, perform complex queries, and manage your Azure Cosmos DB SQL API resources.
Зворотний зв’язок
Надіслати й переглянути відгук про