快速入门:生成 .NET 控制台应用以管理 Azure Cosmos DB SQL API 资源Quickstart: Build a .NET console app to manage Azure Cosmos DB SQL API resources

开始使用适用于 .NET 的 Azure Cosmos DB SQL API 客户端库。Get started with the Azure Cosmos DB SQL API client library for .NET. 按照本文档中的步骤安装 .NET 包,生成应用,并尝试对存储在 Azure Cosmos DB 中的数据执行基本 CRUD 操作的示例代码。Follow the steps in this doc to install the .NET package, build an app, and try out the example code for basic CRUD operations on the data stored in Azure Cosmos DB.

Azure Cosmos DB 是世纪互联提供的多区域分布式多模型数据库服务。Azure Cosmos DB is 21Vianet's multiple-regionally distributed multi-model database service. 使用 Azure Cosmos DB,可以快速创建和查询键/值、文档和图形数据库。You can use Azure Cosmos DB to quickly create and query key/value, document, and graph databases. 使用适用于 .NET 的 Azure Cosmos DB SQL API 客户端库完成以下操作:Use the Azure Cosmos DB SQL API client library for .NET to:

  • 创建 Azure Cosmos 数据库和容器Create an Azure Cosmos database and a container
  • 向容器添加示例数据Add sample data to the container
  • 查询数据Query the data
  • 删除数据库Delete the database

API 参考文档 | 库源代码 | 包 (NuGet)API reference documentation | Library source code | Package (NuGet)

先决条件Prerequisites

设置Setting up

本部分指导你创建 Azure Cosmos 帐户,并设置使用适用于 .NET 的 Azure Cosmos DB SQL API 客户端库以管理资源的项目。This section walks you through creating an Azure Cosmos account and setting up a project that uses Azure Cosmos DB SQL API client library for .NET to manage resources. 本文所述的示例代码创建 FamilyDatabase 数据库,并在该数据库中创建家庭成员(每个家庭成员都是一个项)。The example code described in this article creates a FamilyDatabase database and family members (each family member is an item) within that database. 每个家庭成员都具有 Id, FamilyName, FirstName, LastName, Parents, Children, Address, 等属性。Each family member has properties such as Id, FamilyName, FirstName, LastName, Parents, Children, Address,. LastName 属性用作容器的分区键。The LastName property is used as the partition key for the container.

创建 Azure Cosmos 帐户Create an Azure Cosmos account

以下代码将创建具有会话一致性的 Azure Cosmos 帐户。The following code will create an Azure Cosmos account with session consistency. 该帐户在 China EastChina North 中复制。The account is replicated in China East and China North.


# Set variables for the new SQL API account, database, and container
resourceGroupName='myResourceGroup'
location='chinaeast'
accountName='mysqlapicosmosdb' 
databaseName='FamilyDatabase'
containerName='FamilyContainer'

# Create a resource group
az group create \
    --name $resourceGroupName \
    --location $location

# Create a SQL API Cosmos DB account with session consistency and multi-master enabled
az cosmosdb create \
    --resource-group $resourceGroupName \
    --name $accountName \
    --kind GlobalDocumentDB \
    --locations regionName="chinaeast" failoverPriority=0 --locations regionName="chinanorth" failoverPriority=1 \
    --default-consistency-level "Session" \
    --enable-multiple-write-locations true

新建 .NET 应用Create a new .NET app

在首选编辑器或 IDE 中创建新的 .NET 应用程序。Create a new .NET application in your preferred editor or IDE. 在控制台窗口中,运行以下 DotNet 新命令,创建名为 todo 的新应用。In a console window, run the following dotnet new command to create a new app with the name todo.

dotnet new console --langVersion 7.1 -n todo

将目录更改为新创建的应用文件夹。Change your directory to the newly created app folder. 可使用以下代码生成应用程序:You can build the application with:

cd todo
dotnet build

内部版本的预期输出应如下所示:The expected output from the build should look something like this:

  Restore completed in 100.37 ms for C:\Users\user1\Downloads\CosmosDB_Samples\todo\todo.csproj.
  todo -> C:\Users\user1\Downloads\CosmosDB_Samples\todo\bin\Debug\netcoreapp2.2\todo.dll
  todo -> C:\Users\user1\Downloads\CosmosDB_Samples\todo\bin\Debug\netcoreapp2.2\todo.Views.dll

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:34.17

安装 Azure Cosmos DB 包Install the Azure Cosmos DB package

当仍在应用程序目录中时,使用 DotNet 添加包命令安装适用于 .NET 的 Azure Cosmos DB 客户端库。While still in the application directory, install the Azure Cosmos DB client library for .NET Core by using the dotnet add package command.

dotnet add package Microsoft.Azure.Cosmos

从 Microsoft Azure 门户复制 Azure Cosmos 帐户凭据Copy your Azure Cosmos account credentials from the Azure portal

此示例应用程序需对 Azure Cosmos 帐户进行身份验证。The sample application needs to authenticate to your Azure Cosmos account. 为了进行身份验证,应将 Azure Cosmos 帐户凭据传递给应用程序。To authenticate, you should pass the Azure Cosmos account credentials to the application. 按照以下步骤获取 Azure Cosmos 帐户凭据:Get your Azure Cosmos account credentials by following these steps:

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 导航到 Azure Cosmos 帐户。Navigate to your Azure Cosmos account.

  3. 打开“键”窗格,复制帐户的 URI 和主键 。Open the Keys pane and copy the URI and PRIMARY KEY of your account. 下一步需将 URI 和键值添加到某个环境变量。You will add the URI and keys values to an environment variable in the next step.

设置环境变量Set the environment variables

复制帐户的 URI 和主键以后,请将其保存到运行应用程序的本地计算机的新环境变量中 。After you have copied the URI and PRIMARY KEY of your account, save them to a new environment variable on the local machine running the application. 若要设置环境变量,请打开控制台窗口,并运行以下命令。To set the environment variable, open a console window, and run the following command. 请确保替换 <Your_Azure_Cosmos_account_URI><Your_Azure_Cosmos_account_PRIMARY_KEY> 值。Make sure to replace <Your_Azure_Cosmos_account_URI> and <Your_Azure_Cosmos_account_PRIMARY_KEY> values.

setx EndpointUrl <Your_Azure_Cosmos_account_URI>
setx PrimaryKey <Your_Azure_Cosmos_account_PRIMARY_KEY>

对象模型Object model

在开始生成应用程序之前,先研究 Azure Cosmos DB 中资源的层次结构以及用于创建和访问这些资源的对象模型。Before you start building the application, let's look into the hierarchy of resources in Azure Cosmos DB and the object model used to create and access these resources. Azure Cosmos DB 按以下顺序创建资源:The Azure Cosmos DB creates resources in the following order:

  • Azure Cosmos 帐户Azure Cosmos account
  • 数据库Databases
  • 容器Containers
  • ItemsItems

若要进一步了解不同实体的层次结构,请参阅在 Azure Cosmos DB 中使用数据库、容器和项To learn in more about the hierarchy of different entities, see the working with databases, containers, and items in Azure Cosmos DB article. 使用以下 .NET 类与这些资源进行交互:You will use the following .NET classes to interact with these resources:

  • CosmosClient - 此类为 Azure Cosmos DB 服务提供客户端逻辑表示。CosmosClient - This class provides a client-side logical representation for the Azure Cosmos DB service. 此客户端对象用于对服务进行配置和执行请求。The client object is used to configure and execute requests against the service.

  • CreateDatabaseIfNotExistsAsync - 若数据库资源不存在,则此方法以异步操作的形式创建数据库资源;若数据库资源已存在,则此方法以异步操作的形式获取它。CreateDatabaseIfNotExistsAsync - This method creates (if doesn't exist) or gets (if already exists) a database resource as an asynchronous operation.

  • CreateContainerIfNotExistsAsync - 若容器不存在,则此方法以异步操作的形式创建容器;若容器已存在,则此方法以异步操作的形式获取它。CreateContainerIfNotExistsAsync- - This method creates (if it doesn't exist) or gets (if it already exists) a container as an asynchronous operation. 可查看响应中的状态代码,确定是新创建了容器 (201) 还是返回了现有容器 (200)。You can check the status code from the response to determine whether the container was newly created (201) or an existing container was returned (200).

  • CreateItemAsync - 此方法在容器中创建项。CreateItemAsync - This method creates an item within the container.

  • QueryItemsAsync - 运行查询以获取所需的项。QueryItemsAsync - Runs a query to get the required items. 在此方法中传递 SQL 查询。A SQL query is passed within this method.

  • DeleteAsync - 从 Azure Cosmos 帐户中删除指定的数据库。DeleteAsync - Deletes the specified database from your Azure Cosmos account. DeleteAsync 方法只删除数据库。DeleteAsync method only deletes the database. 应单独处理 Cosmosclient 实例(DeleteDatabaseandCleanupAsync 方法中如此操作)。Disposing of the Cosmosclient instance should happen separately (which it does in the DeleteDatabaseAndCleanupAsync method.

代码示例Code examples

本文所述的示例代码在 Azure Cosmos DB 中创建家庭数据库。The sample code described in this article creates a family database in Azure Cosmos DB. 家庭数据库包含家庭详细信息,例如名称、地址、位置、关联的父母、子女和宠物。The family database contains family details such as name, address, location, the associated parents, children, and pets. 在将数据填充到 Azure Cosmos 帐户之前,请定义家庭项的属性。Before populating the data to your Azure Cosmos account, define the properties of a family item. 在示例应用程序的根级别创建一个名为 Family.cs 的新类,并向其中添加以下代码:Create a new class named Family.cs at the root level of your sample application and add the following code to it:

using Newtonsoft.Json;

namespace todo
{
    public class Family
    {
        [JsonProperty(PropertyName = "id")]
        public string Id { get; set; }
        public string LastName { get; set; }
        public Parent[] Parents { get; set; }
        public Child[] Children { get; set; }
        public Address Address { get; set; }
        public bool IsRegistered { get; set; }
        public override string ToString()
        {
            return JsonConvert.SerializeObject(this);
        }
    }

    public class Parent
    {
        public string FamilyName { get; set; }
        public string FirstName { get; set; }
    }

    public class Child
    {
        public string FamilyName { get; set; }
        public string FirstName { get; set; }
        public string Gender { get; set; }
        public int Grade { get; set; }
        public Pet[] Pets { get; set; }
    }

    public class Pet
    {
        public string GivenName { get; set; }
    }

    public class Address
    {
        public string State { get; set; }
        public string County { get; set; }
        public string City { get; set; }
    }
}

添加 using 指令并定义客户端对象Add the using directives & define the client object

从项目目录,在编辑器中打开 Program.cs 文件,并在应用程序顶部添加以下 using 指令:From the project directory, open the Program.cs file in your editor and add the following using directives at the top of your application:


using System;
using System.Threading.Tasks;
using System.Configuration;
using System.Collections.Generic;
using System.Net;
using Microsoft.Azure.Cosmos;

program.cs file 中添加代码以读取上一步设置的环境变量。To the program.cs file, add code to read the environment variables that you have set in the previous step. 定义 CosmosClientDatabaseContainer 对象。Define the CosmosClient, Database, and the Container objects. 接下来,向调用 GetStartedDemoAsync 方法的主方法添加代码,在该方法中管理 Azure Cosmos 帐户资源。Next add code to the main method that calls the GetStartedDemoAsync method where you manage Azure Cosmos account resources.

namespace todo
{
    public class Program
    {

        /// The Azure Cosmos DB endpoint for running this GetStarted sample.
        private string EndpointUrl = Environment.GetEnvironmentVariable("EndpointUrl");

        /// The primary key for the Azure DocumentDB account.
        private string PrimaryKey = Environment.GetEnvironmentVariable("PrimaryKey");

        // The Cosmos client instance
        private CosmosClient cosmosClient;

        // The database we will create
        private Database database;

        // The container we will create.
        private Container container;

        // The name of the database and container we will create
        private string databaseId = "FamilyDatabase";
        private string containerId = "FamilyContainer";

        public static async Task Main(string[] args)
        {
           try
           {
               Console.WriteLine("Beginning operations...\n");
               Program p = new Program();
               await p.GetStartedDemoAsync();

            }
            catch (CosmosException de)
            {
               Exception baseException = de.GetBaseException();
               Console.WriteLine("{0} error occurred: {1}", de.StatusCode, de);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e);
            }
            finally
            {
                Console.WriteLine("End of demo, press any key to exit.");
                Console.ReadKey();
            }
        }
    }
}

创建数据库Create a database

定义 program.cs 类中的 CreateDatabaseAsync 方法。Define the CreateDatabaseAsync method within the program.cs class. 该方法创建 FamilyDatabase(如果尚不存在)。This method creates the FamilyDatabase if it doesn't already exist.

private async Task CreateDatabaseAsync()
{
    // Create a new database
    this.database = await this.cosmosClient.CreateDatabaseIfNotExistsAsync(databaseId);
    Console.WriteLine("Created Database: {0}\n", this.database.Id);
}

创建容器Create a container

定义 program.cs 类中的 CreateContainerAsync 方法。Define the CreateContainerAsync method within the program.cs class. 该方法创建 FamilyContainer(如果尚不存在)。This method creates the FamilyContainer if it doesn't already exist.

/// Create the container if it does not exist. 
/// Specifiy "/LastName" as the partition key since we're storing family information, to ensure good distribution of requests and storage.
private async Task CreateContainerAsync()
{
    // Create a new container
    this.container = await this.database.CreateContainerIfNotExistsAsync(containerId, "/LastName");
    Console.WriteLine("Created Container: {0}\n", this.container.Id);
}

创建项Create an item

AddItemsToContainerAsync 方法添加以下代码,以创建家庭项:Create a family item by adding the AddItemsToContainerAsync method with the following code:

private async Task AddItemsToContainerAsync()
{
    // Create a family object for the Andersen family
    Family andersenFamily = new Family
    {
        Id = "Andersen.1",
        LastName = "Andersen",
        Parents = new Parent[]
        {
           new Parent { FirstName = "Thomas" },
           new Parent { FirstName = "Mary Kay" }
        },
        Children = new Child[]
        {
           new Child
            {
                FirstName = "Henriette Thaulow",
                Gender = "female",
                Grade = 5,
                Pets = new Pet[]
                {
                    new Pet { GivenName = "Fluffy" }
                }
            }
        },
        Address = new Address { State = "WA", County = "King", City = "Seattle" },
        IsRegistered = false
 };

// Read the item to see if it exists. Note ReadItemAsync will not throw an exception if an item does not exist. Instead, we check the StatusCode property off the response object. 
ItemResponse<Family> andersenFamilyResponse = await this.container.ReadItemAsync<Family>(andersenFamily.Id, new PartitionKey(andersenFamily.LastName));

if (andersenFamilyResponse.StatusCode == HttpStatusCode.NotFound)
{
    // Create an item in the container representing the Andersen family. Note we provide the value of the partition key for this item, which is "Andersen"
    andersenFamilyResponse = await this.container.CreateItemAsync<Family>(andersenFamily, new PartitionKey(andersenFamily.LastName));

    // Note that after creating the item, we can access the body of the item with the Resource property off the ItemResponse. We can also access the RequestCharge property to see the amount of RUs consumed on this request.
    Console.WriteLine("Created item in database with id: {0} Operation consumed {1} RUs.\n", andersenFamilyResponse.Resource.Id, andersenFamilyResponse.RequestCharge);
}
else
{
    Console.WriteLine("Item in database with id: {0} already exists\n", andersenFamilyResponse.Resource.Id);
}

查询项Query the items

插入项后,可以运行查询以获取“Andersen”家庭的详细信息。After inserting an item, you can run a query to get the details of "Andersen" family. 以下代码显示如何直接使用 SQL 查询来执行查询。The following code shows how to execute the query using the SQL query directly. 获取“Anderson”家庭详细信息的 SQL 查询是:SELECT * FROM c WHERE c.LastName = 'Andersen'The SQL query to get the "Anderson" family details is: SELECT * FROM c WHERE c.LastName = 'Andersen'. program.cs 类中定义 QueryItemsAsync 方法,并向其中添加以下代码:Define the QueryItemsAsync method within the program.cs class and add the following code to it:

private async Task QueryItemsAsync()
{
    var sqlQueryText = "SELECT * FROM c WHERE c.LastName = 'Andersen'";

    Console.WriteLine("Running query: {0}\n", sqlQueryText);

    QueryDefinition queryDefinition = new QueryDefinition(sqlQueryText);
    FeedIterator<Family> queryResultSetIterator = this.container.GetItemQueryIterator<Family>(queryDefinition);

    List<Family> families = new List<Family>();

    while (queryResultSetIterator.HasMoreResults)
    {
        FeedResponse<Family> currentResultSet = await queryResultSetIterator.ReadNextAsync();
        foreach (Family family in currentResultSet)
        {
            families.Add(family);
            Console.WriteLine("\tRead {0}\n", family);
        }
    }
}

删除数据库Delete the database

最后,可以使用以下代码删除添加 DeleteDatabaseAndCleanupAsync 方法的数据库:Finally you can delete the database adding the DeleteDatabaseAndCleanupAsync method with the following code:

private async Task DeleteDatabaseAndCleanupAsync()
{
   DatabaseResponse databaseResourceResponse = await this.database.DeleteAsync();
   // Also valid: await this.cosmosClient.Databases["FamilyDatabase"].DeleteAsync();

   Console.WriteLine("Deleted Database: {0}\n", this.databaseId);

   //Dispose of CosmosClient
    this.cosmosClient.Dispose();
}

执行 CRUD 操作Execute the CRUD operations

定义完所有必需方法后,在 GetStartedDemoAsync 方法中执行。After you have defined all the required methods, execute them with in the GetStartedDemoAsync method. 此代码中注释掉了 DeleteDatabaseAndCleanupAsync 方法,因此如果执行该方法,你将看不到任何资源。The DeleteDatabaseAndCleanupAsync method commented out in this code because you will not see any resources if that method is executed. 在 Microsoft Azure 门户中验证已创建 Azure Cosmos DB 资源后,可以取消对其的注释。You can uncomment it after validating that your Azure Cosmos DB resources were created in the Azure portal.

public async Task GetStartedDemoAsync()
{
    // Create a new instance of the Cosmos Client
    this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
    await this.CreateDatabaseAsync();
    await this.CreateContainerAsync();
    await this.AddItemsToContainerAsync();
    await this.QueryItemsAsync();
    await this.ReplaceFamilyItemAsync();
    await this.DeleteFamilyItemAsync();
    //await this.DeleteDatabaseAndCleanupAsync();
}

添加所有必要的方法后,保存 Program.cs 文件。After you add all the required methods, save the Program.cs file.

运行代码Run the code

接下来,生成并运行应用程序以创建 Azure Cosmos DB 资源。Next build and run the application to create the Azure Cosmos DB resources. 请确保打开新的命令提示符窗口,请勿使用用于设置环境变量的实例。Make sure to open a new command prompt window, don't use the same instance that you have used to set the environment variables. 因为未在当前打开的窗口中设置环境变量。Because the environment variables are not set in the current open window. 需要打开新的命令提示符以查看更新。You will need to open a new command prompt to see the updates.

dotnet build
dotnet run

运行应用程序时生成以下输出。The following output is generated when you run the application. 还可以登录到 Microsoft Azure 门户并验证是否已创建资源:You can also sign into the Azure portal and validate that the resources are created:

Created Database: FamilyDatabase

Created Container: FamilyContainer

Created item in database with id: Andersen.1 Operation consumed 11.62 RUs.

Running query: SELECT * FROM c WHERE c.LastName = 'Andersen'

        Read {"id":"Andersen.1","LastName":"Andersen","Parents":[{"FamilyName":null,"FirstName":"Thomas"},{"FamilyName":null,"FirstName":"Mary Kay"}],"Children":[{"FamilyName":null,"FirstName":"Henriette Thaulow","Gender":"female","Grade":5,"Pets":[{"GivenName":"Fluffy"}]}],"Address":{"State":"WA","County":"King","City":"Seattle"},"IsRegistered":false}

End of demo, press any key to exit.

通过登录到 Microsoft Azure 门户来验证是否已创建数据,并查看 Azure Cosmos 帐户中的必需项。You can validate that the data is created by signing into the Azure portal and see the required items in your Azure Cosmos account.

清理资源Clean up resources

若不再需要资源,可以使用 Azure CLI 或 Azure PowerShell 删除 Azure Cosmos 帐户和相应的资源组。When no longer needed, you can use the Azure CLI or Azure PowerShell to remove the Azure Cosmos account and the corresponding resource group. 以下命令显示如何使用 Azure CLI 删除资源组:The following command shows how to delete the resource group by using the Azure CLI:

az group delete -g "myResourceGroup" -l "chinaeast"

后续步骤Next steps

本快速入门介绍了如何创建 Azure Cosmos 帐户、如何使用 .NET Core 应用创建数据库和容器。In this quickstart, you learned how to create an Azure Cosmos account, create a database and a container using a .NET Core app. 现在可以使用以下文章中的说明将其他数据导入到 Azure Cosmos 帐户。You can now import additional data to your Azure Cosmos account with the instructions int the following article.