Quickstart: Use Azure Cosmos DB for NoSQL with Azure SDK for .NET
In this quickstart, you deploy a basic Azure Cosmos DB for Table application using the Azure SDK for .NET. Azure Cosmos DB for Table is a schemaless data store allowing applications to store structured table data in the cloud. You learn how to create tables, rows, and perform basic tasks within your Azure Cosmos DB resource using the Azure SDK for .NET.
API reference documentation | Library source code | Package (NuGet) | Azure Developer CLI
Prerequisites
- Azure Developer CLI
- Docker Desktop
- .NET 9.0
If you don't have an Azure account, create a Trial before you begin.
Initialize the project
Use the Azure Developer CLI (azd
) to create an Azure Cosmos DB for Table account and deploy a containerized sample application. The sample application uses the client library to manage, create, read, and query sample data.
Open a terminal in an empty directory.
If you're not already authenticated, authenticate to the Azure Developer CLI using
azd auth login
. Follow the steps specified by the tool to authenticate to the CLI using your preferred Azure credentials.azd auth login
Use
azd init
to initialize the project.azd init --template cosmos-db-nosql-dotnet-quickstart
During initialization, configure a unique environment name.
Deploy the Azure Cosmos DB account using
azd up
. The Bicep templates also deploy a sample web application.azd up
During the provisioning process, select your subscription, desired location, and target resource group. Wait for the provisioning process to complete. The process can take approximately five minutes.
Once the provisioning of your Azure resources is done, a URL to the running web application is included in the output.
Deploying services (azd deploy) (✓) Done: Deploying service web - Endpoint: <https://[container-app-sub-domain].azurecontainerapps.io> SUCCESS: Your application was provisioned and deployed to Azure in 5 minutes 0 seconds.
Use the URL in the console to navigate to your web application in the browser. Observe the output of the running app.
Install the client library
The client library is available through NuGet, as the Microsoft.Azure.Cosmos
package.
Open a terminal and navigate to the
/src/web
folder.cd ./src/web
If not already installed, install the
Microsoft.Azure.Cosmos
package usingdotnet add package
.dotnet add package Microsoft.Azure.Cosmos --version 3.*
Also, install the
Azure.Identity
package if not already installed.dotnet add package Azure.Identity --version 1.12.*
Open and review the src/web/Cosmos.Samples.NoSQL.Quickstart.Web.csproj file to validate that the
Microsoft.Azure.Cosmos
andAzure.Identity
entries both exist.
Object model
Name | Description |
---|---|
CosmosClient | This class is the primary client class and is used to manage account-wide metadata or databases. |
Database | This class represents a database within the account. |
Container | This class is primarily used to perform read, update, and delete operations on either the container or the items stored within the container. |
Container | This class represents a logical partition key. This class is required for many common operations and queries. |
Code examples
The sample code in the template uses a database named cosmicworks
and container named products
. The products
container contains details such as name, category, quantity, a unique identifier, and a sale flag for each product. The container uses the /category
property as a logical partition key.
Authenticate the client
This sample creates a new instance of the CosmosClient
class and authenticates using a DefaultAzureCredential
instance.
DefaultAzureCredential credential = new();
CosmosClient client = new(
accountEndpoint: "<azure-cosmos-db-nosql-account-endpoint>",
tokenCredential: new DefaultAzureCredential()
);
Get a database
Use client.GetDatabase
to retrieve the existing database named cosmicworks
.
Database database = client.GetDatabase("cosmicworks");
Get a container
Retrieve the existing products
container using database.GetContainer
.
Container container = database.GetContainer("products");
Create an item
Build a C# record type with all of the members you want to serialize into JSON. In this example, the type has a unique identifier, and fields for category, name, quantity, price, and sale.
public record Product(
string id,
string category,
string name,
int quantity,
decimal price,
bool clearance
);
Create an item in the container using container.UpsertItem
. This method "upserts" the item effectively replacing the item if it already exists.
Product item = new(
id: "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
category: "gear-surf-surfboards",
name: "Yamba Surfboard",
quantity: 12,
price: 850.00m,
clearance: false
);
ItemResponse<Product> response = await container.UpsertItemAsync<Product>(
item: item,
partitionKey: new PartitionKey("gear-surf-surfboards")
);
Read an item
Perform a point read operation by using both the unique identifier (id
) and partition key fields. Use container.ReadItem
to efficiently retrieve the specific item.
ItemResponse<Product> response = await container.ReadItemAsync<Product>(
id: "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
partitionKey: new PartitionKey("gear-surf-surfboards")
);
Query items
Perform a query over multiple items in a container using container.GetItemQueryIterator
. Find all items within a specified category using this parameterized query:
SELECT * FROM products p WHERE p.category = @category
string query = "SELECT * FROM products p WHERE p.category = @category"
var query = new QueryDefinition(query)
.WithParameter("@category", "gear-surf-surfboards");
using FeedIterator<Product> feed = container.GetItemQueryIterator<Product>(
queryDefinition: query
);
Parse the paginated results of the query by looping through each page of results using feed.ReadNextAsync
. Use feed.HasMoreResults
to determine if there are any results left at the start of each loop.
List<Product> items = new();
while (feed.HasMoreResults)
{
FeedResponse<Product> response = await feed.ReadNextAsync();
foreach (Product item in response)
{
items.Add(item);
}
}
Clean up resources
When you no longer need the sample application or resources, remove the corresponding deployment and all resources.
azd down