你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
在本快速入门中,你将使用用于 .NET 的 Azure SDK 部署基本的 Azure Cosmos DB for NoSQL 应用程序。 Azure Cosmos DB for NoSQL 是一种无架构数据存储,允许应用程序在云中存储非结构化数据。 使用用于 .NET 的 Azure SDK 查询容器中的数据,并针对单个项执行常见作。
API 参考文档 | 库源代码 | 包 (NuGet) | Azure Developer CLI
先决条件
- Azure Developer CLI
- Docker Desktop
- .NET 9.0
如果没有 Azure 帐户,请在开始前创建一个免费帐户。
初始化项目
使用 Azure 开发人员 CLI (azd) 创建 Azure Cosmos DB for NoSQL 帐户并部署容器化示例应用程序。 示例应用程序使用客户端库来管理、创建、读取和查询示例数据。
- 在空目录中打开终端。 
- 如果尚未经过身份验证,请使用 - azd auth login向 Azure Developer CLI 进行身份验证。 按照该工具指定的步骤,使用首选 Azure 凭据向 CLI 进行身份验证。- azd auth login
- 使用 - azd init来初始化项目。- azd init --template cosmos-db-nosql-dotnet-quickstart
- 在初始化期间,配置唯一的环境名称。 
- 使用 - azd up部署 Azure Cosmos DB 帐户。 Bicep 模板还部署示例 Web 应用程序。- azd up
- 在预配过程中,选择订阅、所需位置和目标资源组。 等待预配过程完成。 此过程可能需要大约 5 分钟。 
- 预配 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.
- 使用控制台中的 URL 在浏览器中导航到 Web 应用程序。 观察正在运行的应用的输出。 
              
               
              
              
            
安装客户端库
客户端库可通过 NuGet 作为 Microsoft.Azure.Cosmos 包使用。
- 打开终端并导航到 - /src/web文件夹。- cd ./src/web
- 使用 - Microsoft.Azure.Cosmos安装- dotnet add package包(如果尚未安装)。- dotnet add package Microsoft.Azure.Cosmos --version 3.*
- 另请安装 - Azure.Identity包(如果尚未安装)。- dotnet add package Azure.Identity --version 1.12.*
- 打开并查看 src/web/Cosmos.Samples.NoSQL.Quickstart.Web.csproj 文件,以验证 和 - Microsoft.Azure.Cosmos条目是否都存在。- Azure.Identity
导入库文件
将 Azure.Identity 和 Microsoft.Azure.Cosmos 命名空间导入应用程序代码。
using Azure.Identity;
using Microsoft.Azure.Cosmos;
对象模型
| 名称 | 描述 | 
|---|---|
| CosmosClient | 此类是主要客户端类,用于管理帐户范围的元数据或数据库。 | 
| Database | 此类表示帐户中的一个数据库。 | 
| Container | 这个类主要用于对容器或容器中存储的项执行读取、更新和删除操作。 | 
| PartitionKey | 此类表示逻辑分区键。 许多常见操作和查询都需要这门课。 | 
代码示例
模板中的示例代码使用名为 cosmicworks 的数据库和名为 products 的容器。 
              products 容器包含每个产品的名称、类别、数量、唯一标识符和销售标志等详细信息。 该容器使用 /category 属性作为逻辑分区键。
验证客户端
此示例创建 CosmosClient 类的新实例并使用 DefaultAzureCredential 实例进行身份验证。
DefaultAzureCredential credential = new();
CosmosClient client = new(
    accountEndpoint: "<azure-cosmos-db-nosql-account-endpoint>",
    tokenCredential: new DefaultAzureCredential()
);
获取数据库
使用 client.GetDatabase 检索名为 cosmicworks 的现有数据库。
Database database = client.GetDatabase("cosmicworks");
获取容器
使用 products 检索现有的 database.GetContainer 容器。
Container container = database.GetContainer("products");
创建项目
使用要序列化为 JSON 的所有成员生成一个 C# 记录类型。 在此示例中,该类型具有唯一标识符以及用于类别、名称、数量、价格和销售的字段。
public record Product(
    string id,
    string category,
    string name,
    int quantity,
    decimal price,
    bool clearance
);
使用 container.UpsertItem 在容器中创建某个项。 如果该项已经存在,此方法会“更新插入”该项,从而有效地替换该项。
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")
);
读取项
同时使用唯一标识符 (id) 和分区键字段来执行点读取操作。 使用 container.ReadItem 以有效检索特定项。
ItemResponse<Product> response = await container.ReadItemAsync<Product>(
    id: "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
    partitionKey: new PartitionKey("gear-surf-surfboards")
);
查询项
使用 container.GetItemQueryIterator 对容器中的多个项执行查询。 使用此参数化查询查找指定类别中的所有项:
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
);
通过使用 feed.ReadNextAsync 循环访问每个结果页来分析查询的分页结果。 在每个循环的开头使用 feed.HasMoreResults 来确定是否还剩下任何结果。
List<Product> items = new();
while (feed.HasMoreResults)
{
    FeedResponse<Product> response = await feed.ReadNextAsync();
    foreach (Product item in response)
    {
        items.Add(item);
    }
}
探索您的数据
使用适用于 Azure Cosmos DB 的 Visual Studio Code 扩展来浏览 NoSQL 数据。 可以执行核心数据库操作,这些操作包括但不限于:
- 使用剪贴簿或查询编辑器执行查询
- 修改、更新、创建和删除项
- 从其他源导入批量数据
- 管理数据库和容器
有关详细信息,请参阅如何使用 Visual Studio Code 扩展来浏览 Azure Cosmos DB for NoSQL 数据。
清理资源
不再需要示例应用程序或资源时,请删除相应的部署和所有资源。
azd down