Quickstart: Azure Cosmos DB for NoSQL library for .NET

APPLIES TO: NoSQL

Get started with the Azure Cosmos DB for NoSQL client library for .NET to query data in your containers and perform common operations on individual items. Follow these steps to deploy a minimal solution to your environment using the Azure Developer CLI.

API reference documentation | Library source code | Package (NuGet) | Azure Developer CLI

Prerequisites

Setting up

Deploy this project's development container to your environment. Then, use the Azure Developer CLI (azd) to create an Azure Cosmos DB for NoSQL account and deploy a containerized sample application. The sample application uses the client library to manage, create, read, and query sample data.

Open in GitHub Codespaces

Open in Dev Container

Important

GitHub accounts include an entitlement of storage and core hours at no cost. For more information, see included storage and core hours for GitHub accounts.

  1. Open a terminal in the root directory of the project.

  2. 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
    
  3. Use azd init to initialize the project.

    azd init --template cosmos-db-nosql-dotnet-quickstart
    

    Note

    This quickstart uses the azure-samples/cosmos-db-nosql-dotnet-quickstart template GitHub repository. The Azure Developer CLI will automatically clone this project to your machine if it is not already there.

  4. During initialization, configure a unique environment name.

    Tip

    The environment name will also be used as the target resource group name. For this quickstart, consider using msdocs-cosmos-db.

  5. Deploy the Azure Cosmos DB account using azd up. The Bicep templates also deploy a sample web application.

    azd up
    
  6. During the provisioning process, select your subscription and desired location. Wait for the provisioning process to complete. The process can take approximately five minutes.

  7. 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.
    
  8. Use the URL in the console to navigate to your web application in the browser. Observe the output of the running app.

    Screenshot of the running web application.

Install the client library

The client library is available through NuGet, as the Microsoft.Azure.Cosmos package.

  1. Open a terminal and navigate to the /src/web folder.

    cd ./src/web
    
  2. If not already installed, install the Microsoft.Azure.Cosmos package using dotnet add package.

    dotnet add package Microsoft.Azure.Cosmos
    
  3. Also, install the Azure.Identity package if not already installed.

    dotnet add package Azure.Identity
    
  4. Open and review the src/web/Cosmos.Samples.NoSQL.Quickstart.Web.csproj file to validate that the Microsoft.Azure.Cosmos and Azure.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

Application requests to most Azure services must be authorized. Use the DefaultAzureCredential type as the preferred way to implement a passwordless connection between your applications and Azure Cosmos DB for NoSQL. DefaultAzureCredential supports multiple authentication methods and determines which method should be used at runtime.

Important

You can also authorize requests to Azure services using passwords, connection strings, or other credentials directly. However, this approach should be used with caution. Developers must be diligent to never expose these secrets in an unsecure location. Anyone who gains access to the password or secret key is able to authenticate to the database service. DefaultAzureCredential offers improved management and security benefits over the account key to allow passwordless authentication without the risk of storing keys.

This sample creates a new instance of the CosmosClient class and authenticates using a DefaultAzureCredential instance.

using Azure.Identity;
using Microsoft.Azure.Cosmos;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();

if (builder.Environment.IsDevelopment())
{
    builder.Services.AddSingleton<CosmosClient>((_) =>
    {
        // <create_client>
        CosmosClient client = new(
            accountEndpoint: builder.Configuration["AZURE_COSMOS_DB_NOSQL_ENDPOINT"]!,
            tokenCredential: new DefaultAzureCredential()
        );
        // </create_client>
        return client;
    });
}
else
{
    builder.Services.AddSingleton<CosmosClient>((_) =>
    {
        // <create_client_client_id>
        CosmosClient client = new(
            accountEndpoint: builder.Configuration["AZURE_COSMOS_DB_NOSQL_ENDPOINT"]!,
            tokenCredential: new DefaultAzureCredential(
                new DefaultAzureCredentialOptions()
                {
                    ManagedIdentityClientId = builder.Configuration["AZURE_MANAGED_IDENTITY_CLIENT_ID"]!
                }
            )
        );
        // </create_client_client_id>
        return client;
    });
}

builder.Services.AddTransient<ICosmosDbService, CosmosDbService>();

var app = builder.Build();

app.UseDeveloperExceptionPage();

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();

Get a database

Use client.GetDatabase to retrieve the existing database named cosmicworks.

using Cosmos.Samples.NoSQL.Quickstart.Web.Models;
using Microsoft.Azure.Cosmos;

internal interface ICosmosDbService
{
    Task RunDemoAsync(Func<string, Task> writeOutputAync);

    string GetEndpoint();
}

internal sealed class CosmosDbService : ICosmosDbService
{
    private readonly CosmosClient client;

    public CosmosDbService(CosmosClient client)
    {
        this.client = client;
    }

    public string GetEndpoint() => $"{client.Endpoint}";

    public async Task RunDemoAsync(Func<string, Task> writeOutputAync)
    {
        // <get_database>
        Database database = client.GetDatabase("cosmicworks");
        // </get_database>
        database = await database.ReadAsync();
        await writeOutputAync($"Get database:\t{database.Id}");

        // <get_container>
        Container container = database.GetContainer("products");
        // </get_container>
        container = await container.ReadContainerAsync();
        await writeOutputAync($"Get container:\t{container.Id}");

        {
            // <create_item>
            Product item = new(
                id: "68719518391",
                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")
            );
            // </create_item>            
            await writeOutputAync($"Upserted item:\t{response.Resource}");
            await writeOutputAync($"Status code:\t{response.StatusCode}");
            await writeOutputAync($"Request charge:\t{response.RequestCharge:0.00}");
        }

        {
            Product item = new(
                id: "68719518371",
                category: "gear-surf-surfboards",
                name: "Kiama Classic Surfboard",
                quantity: 25,
                price: 790.00m,
                clearance: false
            );

            ItemResponse<Product> response = await container.UpsertItemAsync<Product>(
                item: item,
                partitionKey: new PartitionKey("gear-surf-surfboards")
            );
            await writeOutputAync($"Upserted item:\t{response.Resource}");
            await writeOutputAync($"Status code:\t{response.StatusCode}");
            await writeOutputAync($"Request charge:\t{response.RequestCharge:0.00}");
        }

        {
            // <read_item>
            ItemResponse<Product> response = await container.ReadItemAsync<Product>(
                id: "68719518391",
                partitionKey: new PartitionKey("gear-surf-surfboards")
            );
            // </read_item>
            await writeOutputAync($"Read item id:\t{response.Resource.id}");
            await writeOutputAync($"Read item:\t{response.Resource}");
            await writeOutputAync($"Status code:\t{response.StatusCode}");
            await writeOutputAync($"Request charge:\t{response.RequestCharge:0.00}");
        }

        {
            // <query_items>
            var query = new QueryDefinition(
                query: "SELECT * FROM products p WHERE p.category = @category"
            )
                .WithParameter("@category", "gear-surf-surfboards");

            using FeedIterator<Product> feed = container.GetItemQueryIterator<Product>(
                queryDefinition: query
            );
            // </query_items>
            await writeOutputAync($"Ran query:\t{query.QueryText}");

            // <parse_results>
            List<Product> items = new();
            double requestCharge = 0d;
            while (feed.HasMoreResults)
            {
                FeedResponse<Product> response = await feed.ReadNextAsync();
                foreach (Product item in response)
                {
                    items.Add(item);
                }
                requestCharge += response.RequestCharge;
            }
            // </parse_results>

            foreach (var item in items)
            {
                await writeOutputAync($"Found item:\t{item.name}\t[{item.id}]");
            }
            await writeOutputAync($"Request charge:\t{requestCharge:0.00}");
        }
    }
}

Get a container

Retrieve the existing products container using database.GetContainer.

using Cosmos.Samples.NoSQL.Quickstart.Web.Models;
using Microsoft.Azure.Cosmos;

internal interface ICosmosDbService
{
    Task RunDemoAsync(Func<string, Task> writeOutputAync);

    string GetEndpoint();
}

internal sealed class CosmosDbService : ICosmosDbService
{
    private readonly CosmosClient client;

    public CosmosDbService(CosmosClient client)
    {
        this.client = client;
    }

    public string GetEndpoint() => $"{client.Endpoint}";

    public async Task RunDemoAsync(Func<string, Task> writeOutputAync)
    {
        // <get_database>
        Database database = client.GetDatabase("cosmicworks");
        // </get_database>
        database = await database.ReadAsync();
        await writeOutputAync($"Get database:\t{database.Id}");

        // <get_container>
        Container container = database.GetContainer("products");
        // </get_container>
        container = await container.ReadContainerAsync();
        await writeOutputAync($"Get container:\t{container.Id}");

        {
            // <create_item>
            Product item = new(
                id: "68719518391",
                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")
            );
            // </create_item>            
            await writeOutputAync($"Upserted item:\t{response.Resource}");
            await writeOutputAync($"Status code:\t{response.StatusCode}");
            await writeOutputAync($"Request charge:\t{response.RequestCharge:0.00}");
        }

        {
            Product item = new(
                id: "68719518371",
                category: "gear-surf-surfboards",
                name: "Kiama Classic Surfboard",
                quantity: 25,
                price: 790.00m,
                clearance: false
            );

            ItemResponse<Product> response = await container.UpsertItemAsync<Product>(
                item: item,
                partitionKey: new PartitionKey("gear-surf-surfboards")
            );
            await writeOutputAync($"Upserted item:\t{response.Resource}");
            await writeOutputAync($"Status code:\t{response.StatusCode}");
            await writeOutputAync($"Request charge:\t{response.RequestCharge:0.00}");
        }

        {
            // <read_item>
            ItemResponse<Product> response = await container.ReadItemAsync<Product>(
                id: "68719518391",
                partitionKey: new PartitionKey("gear-surf-surfboards")
            );
            // </read_item>
            await writeOutputAync($"Read item id:\t{response.Resource.id}");
            await writeOutputAync($"Read item:\t{response.Resource}");
            await writeOutputAync($"Status code:\t{response.StatusCode}");
            await writeOutputAync($"Request charge:\t{response.RequestCharge:0.00}");
        }

        {
            // <query_items>
            var query = new QueryDefinition(
                query: "SELECT * FROM products p WHERE p.category = @category"
            )
                .WithParameter("@category", "gear-surf-surfboards");

            using FeedIterator<Product> feed = container.GetItemQueryIterator<Product>(
                queryDefinition: query
            );
            // </query_items>
            await writeOutputAync($"Ran query:\t{query.QueryText}");

            // <parse_results>
            List<Product> items = new();
            double requestCharge = 0d;
            while (feed.HasMoreResults)
            {
                FeedResponse<Product> response = await feed.ReadNextAsync();
                foreach (Product item in response)
                {
                    items.Add(item);
                }
                requestCharge += response.RequestCharge;
            }
            // </parse_results>

            foreach (var item in items)
            {
                await writeOutputAync($"Found item:\t{item.name}\t[{item.id}]");
            }
            await writeOutputAync($"Request charge:\t{requestCharge:0.00}");
        }
    }
}

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.

namespace Cosmos.Samples.NoSQL.Quickstart.Web.Models;

// <model>
public record Product(
    string id,
    string category,
    string name,
    int quantity,
    decimal price,
    bool clearance
);
// </model>

Create an item in the container using container.UpsertItem. This method "upserts" the item effectively replacing the item if it already exists.

using Cosmos.Samples.NoSQL.Quickstart.Web.Models;
using Microsoft.Azure.Cosmos;

internal interface ICosmosDbService
{
    Task RunDemoAsync(Func<string, Task> writeOutputAync);

    string GetEndpoint();
}

internal sealed class CosmosDbService : ICosmosDbService
{
    private readonly CosmosClient client;

    public CosmosDbService(CosmosClient client)
    {
        this.client = client;
    }

    public string GetEndpoint() => $"{client.Endpoint}";

    public async Task RunDemoAsync(Func<string, Task> writeOutputAync)
    {
        // <get_database>
        Database database = client.GetDatabase("cosmicworks");
        // </get_database>
        database = await database.ReadAsync();
        await writeOutputAync($"Get database:\t{database.Id}");

        // <get_container>
        Container container = database.GetContainer("products");
        // </get_container>
        container = await container.ReadContainerAsync();
        await writeOutputAync($"Get container:\t{container.Id}");

        {
            // <create_item>
            Product item = new(
                id: "68719518391",
                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")
            );
            // </create_item>            
            await writeOutputAync($"Upserted item:\t{response.Resource}");
            await writeOutputAync($"Status code:\t{response.StatusCode}");
            await writeOutputAync($"Request charge:\t{response.RequestCharge:0.00}");
        }

        {
            Product item = new(
                id: "68719518371",
                category: "gear-surf-surfboards",
                name: "Kiama Classic Surfboard",
                quantity: 25,
                price: 790.00m,
                clearance: false
            );

            ItemResponse<Product> response = await container.UpsertItemAsync<Product>(
                item: item,
                partitionKey: new PartitionKey("gear-surf-surfboards")
            );
            await writeOutputAync($"Upserted item:\t{response.Resource}");
            await writeOutputAync($"Status code:\t{response.StatusCode}");
            await writeOutputAync($"Request charge:\t{response.RequestCharge:0.00}");
        }

        {
            // <read_item>
            ItemResponse<Product> response = await container.ReadItemAsync<Product>(
                id: "68719518391",
                partitionKey: new PartitionKey("gear-surf-surfboards")
            );
            // </read_item>
            await writeOutputAync($"Read item id:\t{response.Resource.id}");
            await writeOutputAync($"Read item:\t{response.Resource}");
            await writeOutputAync($"Status code:\t{response.StatusCode}");
            await writeOutputAync($"Request charge:\t{response.RequestCharge:0.00}");
        }

        {
            // <query_items>
            var query = new QueryDefinition(
                query: "SELECT * FROM products p WHERE p.category = @category"
            )
                .WithParameter("@category", "gear-surf-surfboards");

            using FeedIterator<Product> feed = container.GetItemQueryIterator<Product>(
                queryDefinition: query
            );
            // </query_items>
            await writeOutputAync($"Ran query:\t{query.QueryText}");

            // <parse_results>
            List<Product> items = new();
            double requestCharge = 0d;
            while (feed.HasMoreResults)
            {
                FeedResponse<Product> response = await feed.ReadNextAsync();
                foreach (Product item in response)
                {
                    items.Add(item);
                }
                requestCharge += response.RequestCharge;
            }
            // </parse_results>

            foreach (var item in items)
            {
                await writeOutputAync($"Found item:\t{item.name}\t[{item.id}]");
            }
            await writeOutputAync($"Request charge:\t{requestCharge:0.00}");
        }
    }
}

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.

using Cosmos.Samples.NoSQL.Quickstart.Web.Models;
using Microsoft.Azure.Cosmos;

internal interface ICosmosDbService
{
    Task RunDemoAsync(Func<string, Task> writeOutputAync);

    string GetEndpoint();
}

internal sealed class CosmosDbService : ICosmosDbService
{
    private readonly CosmosClient client;

    public CosmosDbService(CosmosClient client)
    {
        this.client = client;
    }

    public string GetEndpoint() => $"{client.Endpoint}";

    public async Task RunDemoAsync(Func<string, Task> writeOutputAync)
    {
        // <get_database>
        Database database = client.GetDatabase("cosmicworks");
        // </get_database>
        database = await database.ReadAsync();
        await writeOutputAync($"Get database:\t{database.Id}");

        // <get_container>
        Container container = database.GetContainer("products");
        // </get_container>
        container = await container.ReadContainerAsync();
        await writeOutputAync($"Get container:\t{container.Id}");

        {
            // <create_item>
            Product item = new(
                id: "68719518391",
                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")
            );
            // </create_item>            
            await writeOutputAync($"Upserted item:\t{response.Resource}");
            await writeOutputAync($"Status code:\t{response.StatusCode}");
            await writeOutputAync($"Request charge:\t{response.RequestCharge:0.00}");
        }

        {
            Product item = new(
                id: "68719518371",
                category: "gear-surf-surfboards",
                name: "Kiama Classic Surfboard",
                quantity: 25,
                price: 790.00m,
                clearance: false
            );

            ItemResponse<Product> response = await container.UpsertItemAsync<Product>(
                item: item,
                partitionKey: new PartitionKey("gear-surf-surfboards")
            );
            await writeOutputAync($"Upserted item:\t{response.Resource}");
            await writeOutputAync($"Status code:\t{response.StatusCode}");
            await writeOutputAync($"Request charge:\t{response.RequestCharge:0.00}");
        }

        {
            // <read_item>
            ItemResponse<Product> response = await container.ReadItemAsync<Product>(
                id: "68719518391",
                partitionKey: new PartitionKey("gear-surf-surfboards")
            );
            // </read_item>
            await writeOutputAync($"Read item id:\t{response.Resource.id}");
            await writeOutputAync($"Read item:\t{response.Resource}");
            await writeOutputAync($"Status code:\t{response.StatusCode}");
            await writeOutputAync($"Request charge:\t{response.RequestCharge:0.00}");
        }

        {
            // <query_items>
            var query = new QueryDefinition(
                query: "SELECT * FROM products p WHERE p.category = @category"
            )
                .WithParameter("@category", "gear-surf-surfboards");

            using FeedIterator<Product> feed = container.GetItemQueryIterator<Product>(
                queryDefinition: query
            );
            // </query_items>
            await writeOutputAync($"Ran query:\t{query.QueryText}");

            // <parse_results>
            List<Product> items = new();
            double requestCharge = 0d;
            while (feed.HasMoreResults)
            {
                FeedResponse<Product> response = await feed.ReadNextAsync();
                foreach (Product item in response)
                {
                    items.Add(item);
                }
                requestCharge += response.RequestCharge;
            }
            // </parse_results>

            foreach (var item in items)
            {
                await writeOutputAync($"Found item:\t{item.name}\t[{item.id}]");
            }
            await writeOutputAync($"Request charge:\t{requestCharge:0.00}");
        }
    }
}

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
using Cosmos.Samples.NoSQL.Quickstart.Web.Models;
using Microsoft.Azure.Cosmos;

internal interface ICosmosDbService
{
    Task RunDemoAsync(Func<string, Task> writeOutputAync);

    string GetEndpoint();
}

internal sealed class CosmosDbService : ICosmosDbService
{
    private readonly CosmosClient client;

    public CosmosDbService(CosmosClient client)
    {
        this.client = client;
    }

    public string GetEndpoint() => $"{client.Endpoint}";

    public async Task RunDemoAsync(Func<string, Task> writeOutputAync)
    {
        // <get_database>
        Database database = client.GetDatabase("cosmicworks");
        // </get_database>
        database = await database.ReadAsync();
        await writeOutputAync($"Get database:\t{database.Id}");

        // <get_container>
        Container container = database.GetContainer("products");
        // </get_container>
        container = await container.ReadContainerAsync();
        await writeOutputAync($"Get container:\t{container.Id}");

        {
            // <create_item>
            Product item = new(
                id: "68719518391",
                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")
            );
            // </create_item>            
            await writeOutputAync($"Upserted item:\t{response.Resource}");
            await writeOutputAync($"Status code:\t{response.StatusCode}");
            await writeOutputAync($"Request charge:\t{response.RequestCharge:0.00}");
        }

        {
            Product item = new(
                id: "68719518371",
                category: "gear-surf-surfboards",
                name: "Kiama Classic Surfboard",
                quantity: 25,
                price: 790.00m,
                clearance: false
            );

            ItemResponse<Product> response = await container.UpsertItemAsync<Product>(
                item: item,
                partitionKey: new PartitionKey("gear-surf-surfboards")
            );
            await writeOutputAync($"Upserted item:\t{response.Resource}");
            await writeOutputAync($"Status code:\t{response.StatusCode}");
            await writeOutputAync($"Request charge:\t{response.RequestCharge:0.00}");
        }

        {
            // <read_item>
            ItemResponse<Product> response = await container.ReadItemAsync<Product>(
                id: "68719518391",
                partitionKey: new PartitionKey("gear-surf-surfboards")
            );
            // </read_item>
            await writeOutputAync($"Read item id:\t{response.Resource.id}");
            await writeOutputAync($"Read item:\t{response.Resource}");
            await writeOutputAync($"Status code:\t{response.StatusCode}");
            await writeOutputAync($"Request charge:\t{response.RequestCharge:0.00}");
        }

        {
            // <query_items>
            var query = new QueryDefinition(
                query: "SELECT * FROM products p WHERE p.category = @category"
            )
                .WithParameter("@category", "gear-surf-surfboards");

            using FeedIterator<Product> feed = container.GetItemQueryIterator<Product>(
                queryDefinition: query
            );
            // </query_items>
            await writeOutputAync($"Ran query:\t{query.QueryText}");

            // <parse_results>
            List<Product> items = new();
            double requestCharge = 0d;
            while (feed.HasMoreResults)
            {
                FeedResponse<Product> response = await feed.ReadNextAsync();
                foreach (Product item in response)
                {
                    items.Add(item);
                }
                requestCharge += response.RequestCharge;
            }
            // </parse_results>

            foreach (var item in items)
            {
                await writeOutputAync($"Found item:\t{item.name}\t[{item.id}]");
            }
            await writeOutputAync($"Request charge:\t{requestCharge:0.00}");
        }
    }
}

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.

using Cosmos.Samples.NoSQL.Quickstart.Web.Models;
using Microsoft.Azure.Cosmos;

internal interface ICosmosDbService
{
    Task RunDemoAsync(Func<string, Task> writeOutputAync);

    string GetEndpoint();
}

internal sealed class CosmosDbService : ICosmosDbService
{
    private readonly CosmosClient client;

    public CosmosDbService(CosmosClient client)
    {
        this.client = client;
    }

    public string GetEndpoint() => $"{client.Endpoint}";

    public async Task RunDemoAsync(Func<string, Task> writeOutputAync)
    {
        // <get_database>
        Database database = client.GetDatabase("cosmicworks");
        // </get_database>
        database = await database.ReadAsync();
        await writeOutputAync($"Get database:\t{database.Id}");

        // <get_container>
        Container container = database.GetContainer("products");
        // </get_container>
        container = await container.ReadContainerAsync();
        await writeOutputAync($"Get container:\t{container.Id}");

        {
            // <create_item>
            Product item = new(
                id: "68719518391",
                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")
            );
            // </create_item>            
            await writeOutputAync($"Upserted item:\t{response.Resource}");
            await writeOutputAync($"Status code:\t{response.StatusCode}");
            await writeOutputAync($"Request charge:\t{response.RequestCharge:0.00}");
        }

        {
            Product item = new(
                id: "68719518371",
                category: "gear-surf-surfboards",
                name: "Kiama Classic Surfboard",
                quantity: 25,
                price: 790.00m,
                clearance: false
            );

            ItemResponse<Product> response = await container.UpsertItemAsync<Product>(
                item: item,
                partitionKey: new PartitionKey("gear-surf-surfboards")
            );
            await writeOutputAync($"Upserted item:\t{response.Resource}");
            await writeOutputAync($"Status code:\t{response.StatusCode}");
            await writeOutputAync($"Request charge:\t{response.RequestCharge:0.00}");
        }

        {
            // <read_item>
            ItemResponse<Product> response = await container.ReadItemAsync<Product>(
                id: "68719518391",
                partitionKey: new PartitionKey("gear-surf-surfboards")
            );
            // </read_item>
            await writeOutputAync($"Read item id:\t{response.Resource.id}");
            await writeOutputAync($"Read item:\t{response.Resource}");
            await writeOutputAync($"Status code:\t{response.StatusCode}");
            await writeOutputAync($"Request charge:\t{response.RequestCharge:0.00}");
        }

        {
            // <query_items>
            var query = new QueryDefinition(
                query: "SELECT * FROM products p WHERE p.category = @category"
            )
                .WithParameter("@category", "gear-surf-surfboards");

            using FeedIterator<Product> feed = container.GetItemQueryIterator<Product>(
                queryDefinition: query
            );
            // </query_items>
            await writeOutputAync($"Ran query:\t{query.QueryText}");

            // <parse_results>
            List<Product> items = new();
            double requestCharge = 0d;
            while (feed.HasMoreResults)
            {
                FeedResponse<Product> response = await feed.ReadNextAsync();
                foreach (Product item in response)
                {
                    items.Add(item);
                }
                requestCharge += response.RequestCharge;
            }
            // </parse_results>

            foreach (var item in items)
            {
                await writeOutputAync($"Found item:\t{item.name}\t[{item.id}]");
            }
            await writeOutputAync($"Request charge:\t{requestCharge:0.00}");
        }
    }
}

Clean up resources

When you no longer need the sample application or resources, remove the corresponding deployment and all resources.

azd down

In GitHub Codespaces, delete the running codespace to maximize your storage and core entitlements.

Next step