从 Windows 应用使用 Cosmos DB 数据库

本文包含启用在 Windows 应用中使用 Cosmos DB 数据库功能所需的步骤。 另外,本文还包含一个小的代码片段,演示如何在代码中与数据库交互。

设置解决方案

此示例可与任何 WPF、Windows 窗体、WinUI 3 和 UWP 项目结合使用,将 Windows 应用连接到 Cosmos DB 数据库。 请按照以下步骤安装包,并试用一些基本任务的示例代码。

打开“程序包管理器控制台”(“视图”->“其他窗口”->“程序包管理器控制台”)。 使用命令 Install-Package Microsoft.Azure.Cosmos 安装适用于 .NET 的 Azure Cosmos DB for NoSQL 客户端库的 NuGet 包。 这样就可以通过编程方式访问 Cosmos DB 数据库。

生成项目并确保生成成功且没有错误。

接下来,需要在 Azure 中创建一个 Cosmos DB 实例。 可以按照在 Azure Cosmos DB 中创建 NoSQL 数据库帐户中的步骤执行此操作。

使用示例代码使用 Cosmos DB

以下示例代码从 Azure 中的 Cosmos DB 实例获取容器,然后向该容器添加一个新项。 然后,它使用 Cosmos DB 的 NoSQL 查询 API 从容器中检索项并输出响应状态。 请注意,需要根据在上一部分中创建的 Cosmos DB 实例自定义终结点、身份验证密钥和数据库名称。

注意

有关完整示例(包括有关所需 Cosmos DB 设置和配置的信息),请参阅使用 Azure Cosmos DB for NoSQL 开发 .NET 控制台应用程序

using Microsoft.Azure.Cosmos;

...

public async Task CosmosSample(string endpoint, string authKey)
{
    // CONNECT
    var client = new CosmosClient(
        accountEndpoint: endpoint,
        authKeyOrResourceToken: authKey
    );
    Database database = client.GetDatabase("sample_customers");
    ContainerProperties properties = new(
        id: "customers",
        partitionKeyPath: "/location"
    );
    Container container = await database.CreateContainerIfNotExistsAsync(properties);

    // WRITE DATA
    string customerId = "1234";
    string state = "WA";
    var customer = new
    {
        id = customerId,
        name = "John Doe",
        location = state
    };
    var createResponse = await container.CreateItemAsync(customer);
    Console.WriteLine($"[Status code: {createResponse.StatusCode}]\t{customerId}");

    // READ DATA
    string sql = "SELECT * FROM customers c WHERE c.id = @id";
    var query = new QueryDefinition(
        query: sql
    ).WithParameter("@id", customerId);
    using var feed = container.GetItemQueryIterator<dynamic>(queryDefinition: query);
    var queryResponse = await feed.ReadNextAsync();
    Console.WriteLine($"[Status code: {queryResponse.StatusCode}]\t{customerId}");
}

请参阅