快速入门:适用于 .NET 的 Azure Cosmos DB for NoSQL 库

适用范围: NoSQL

开始使用适用于 .NET 的 Azure Cosmos DB for NoSQL 客户端库来查询容器中的数据并对各个项执行常见操作。 请按照以下步骤使用 Azure Developer CLI 将最小解决方案部署到环境。

API 参考文档 | 库源代码 | 包 (NuGet) | Azure Developer CLI

先决条件

设置

将此项目的开发容器部署到环境中。 然后,使用 Azure Developer CLI (azd) 创建 Azure Cosmos DB for NoSQL 帐户并部署容器化示例应用程序。 示例应用程序使用客户端库来管理、创建、读取和查询示例数据。

Open in GitHub Codespaces

Open in Dev Container

重要

GitHub 帐户包括使用免费的存储和核心小时数的权利。 有关详细信息,请参阅包含的 GitHub 帐户存储和核心小时数

  1. 在项目的根目录中打开终端。

  2. 使用 azd auth login 向 Azure Developer CLI 进行身份验证。 按照该工具指定的步骤,使用首选 Azure 凭据向 CLI 进行身份验证。

    azd auth login
    
  3. 使用 azd init 来初始化项目。

    azd init
    
  4. 在初始化期间,配置唯一的环境名称。

    提示

    环境名称也将用作目标资源组名称。 对于本快速入门,请考虑使用 msdocs-cosmos-db-nosql

  5. 使用 azd up 部署 Azure Cosmos DB for NoSQL 帐户。 Bicep 模板还部署示例 Web 应用程序。

    azd up
    
  6. 在预配过程中,选择订阅和所需位置。 等待预配过程完成。 此过程可能需要大约 5 分钟

  7. 预配 Azure 资源后,输出中将包含指向正在运行的 Web 应用程序的 URL。

    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. 使用控制台中的 URL 在浏览器中导航到 Web 应用程序。 观察正在运行的应用的输出。

    Screenshot of the running web application.

安装客户端库

客户端库可通过 NuGet 作为 Microsoft.Azure.Cosmos 包使用。

  1. 打开终端并导航到 /src/web 文件夹。

    cd ./src/web
    
  2. 使用 dotnet add package 安装 Microsoft.Azure.Cosmos 包(如果尚未安装)。

    dotnet add package Microsoft.Azure.Cosmos
    
  3. 另请安装 Azure.Identity 包(如果尚未安装)。

    dotnet add package Azure.Identity
    
  4. 打开并查看 src/web/Cosmos.Samples.NoSQL.Quickstart.Web.csproj 文件,以验证 Microsoft.Azure.CosmosAzure.Identity 条目是否都存在。

对象模型

名称 描述
CosmosClient 此类是主要客户端类,用于管理帐户范围的元数据或数据库。
数据库 此类表示帐户内的数据库。
容器 此类主要用于对容器或容器中存储的项执行读取、更新和删除操作。
容器 此类表示逻辑分区键。 许多常见操作和查询都需要此类。

代码示例

模板中的示例代码使用名为 cosmicworks 的数据库和名为 products 的容器。 products 容器包含每个产品的名称、类别、数量、唯一标识符和销售标志等详细信息。 该容器使用 /category 属性作为逻辑分区键。

验证客户端

对大多数 Azure 服务的应用程序请求必须获得授权。 使用 DefaultAzureCredential 类型作为在应用程序和 Azure Cosmos DB for NoSQL 之间实现无密码连接的首选方式。 DefaultAzureCredential 支持多种身份验证方法,并确定应在运行时使用哪种方法。

重要

还可以直接使用密码、连接字符串或其他凭据授权对 Azure 服务的请求。 但是,应谨慎使用此方法。 开发人员必须尽量避免在不安全的位置公开这些机密。 任何可获得密码或密钥的人员都可向数据库服务进行身份验证。 DefaultAzureCredential 提供比帐户密钥更好的管理和安全优势,可以在不冒存储密钥的风险的情况下实现无密码身份验证。

此示例创建 CosmosClient 类的新实例并使用 DefaultAzureCredential 实例进行身份验证。

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();

获取数据库

使用 client.GetDatabase 检索名为 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}");
        }
    }
}

获取容器

使用 database.GetContainer 检索现有的 products 容器。

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}");
        }
    }
}

创建项

使用要序列化为 JSON 的所有成员生成一个 C# 记录类型。 在此示例中,该类型具有唯一标识符以及用于类别、名称、数量、价格和销售的字段。

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

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

使用 container.UpsertItem 在容器中创建某个项。 此方法会“更新插入”该项,有效地替换该项(如果该项已存在)。

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}");
        }
    }
}

读取项

同时使用唯一标识符 (id) 和分区键字段来执行点读取操作。 使用 container.ReadItem 以有效检索特定项。

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}");
        }
    }
}

查询项

使用 container.GetItemQueryIterator 对容器中的多个项执行查询。 使用此参数化查询查找指定类别中的所有项:

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}");
        }
    }
}

通过使用 feed.ReadNextAsync 循环访问每个结果页来分析查询的分页结果。 在每个循环的开头使用 feed.HasMoreResults 来确定是否还剩下任何结果。

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}");
        }
    }
}

清理资源

不再需要示例应用程序或资源时,请删除相应的部署和所有资源。

azd down

在 GitHub Codespaces 中,删除正在运行的 codespace,从而将存储和核心权利最大化。

下一步