生成一个用于在 Azure Cosmos DB SQL API 帐户中管理数据的 .NET 控制台应用Build a .NET console app to manage data in Azure Cosmos DB SQL API account

欢迎使用 Azure Cosmos DB SQL API 入门教程。Welcome to the Azure Cosmos DB SQL API get started tutorial. 学习本教程后,将拥有一个可创建并查询 Azure Cosmos DB 资源的控制台应用程序。After following this tutorial, you'll have a console application that creates and queries Azure Cosmos DB resources.

本教程使用 3.0 版或更高版的 Azure Cosmos DB .NET SDKThis tutorial uses version 3.0 or later of the Azure Cosmos DB .NET SDK. 可以使用 .NET Framework 或 .NET CoreYou can work with .NET Framework or .NET Core.

本教程的内容包括:This tutorial covers:

  • 创建并连接到 Azure Cosmos 帐户Creating and connecting to an Azure Cosmos account
  • 在 Visual Studio 中配置项目Configuring your project in Visual Studio
  • 创建数据库和容器Creating a database and a container
  • 向容器添加项Adding items to the container
  • 查询容器Querying the container
  • 对项执行创建、读取、更新和删除 (CRUD) 操作Performing create, read, update, and delete (CRUD) operations on the item
  • 删除数据库Deleting the database

没有时间?Don't have time? 不必担心!Don't worry! 可在 GitHub上获取完整的解决方案。The complete solution is available on GitHub. 有关快速说明,请转到“获取完整的教程解决方案”部分Jump to the Get the complete tutorial solution section for quick instructions.

现在,让我们开始吧!Now let's get started!

先决条件Prerequisites

步骤 1:创建 Azure Cosmos DB 帐户Step 1: Create an Azure Cosmos DB account

创建 Azure Cosmos DB 帐户。Let's create an Azure Cosmos DB account. 如果已经有要使用的帐户,请跳过此部分。If you already have an account you want to use, skip this section. 若要使用 Azure Cosmos DB 模拟器,请按照 Azure Cosmos DB 模拟器中的步骤设置该模拟器。To use the Azure Cosmos DB Emulator, follow the steps at Azure Cosmos DB Emulator to set up the emulator. 然后跳转到步骤 2:设置 Visual Studio 项目Then skip ahead to Step 2: Set up your Visual Studio project.

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

  2. 选择“创建资源” > “数据库” > “Azure Cosmos DB”。Select Create a resource > Databases > Azure Cosmos DB.

    Azure 门户“数据库”窗格

  3. 在“创建 Azure Cosmos DB 帐户”页上,输入新 Azure Cosmos 帐户的基本设置 。On the Create Azure Cosmos DB Account page, enter the basic settings for the new Azure Cosmos account.

    设置Setting Value DescriptionDescription
    订阅Subscription 订阅名称Subscription name 选择要用于此 Azure Cosmos 帐户的 Azure 订阅。Select the Azure subscription that you want to use for this Azure Cosmos account.
    资源组Resource Group 资源组名称Resource group name 选择一个资源组,或者选择“新建”,然后输入新资源组的唯一名称。 Select a resource group, or select Create new, then enter a unique name for the new resource group.
    帐户名Account Name 唯一的名称A unique name 输入标识此 Azure Cosmos 帐户的名称。Enter a name to identify your Azure Cosmos account. 由于 documents.azure.cn 字符串将追加到所提供的 ID 后面以创建 URI,因此,请使用唯一的 ID。Because documents.azure.cn is appended to the ID that you provide to create your URI, use a unique ID.

    ID 只能包含小写字母、数字和连字符 (-) 字符。The ID can only contain lowercase letters, numbers, and the hyphen (-) character. 它的长度必须介于 3 到 31 个字符之间。It must be between 3-31 characters in length.
    APIAPI 要创建的帐户的类型The type of account to create 选择“Core (SQL)”,以便使用 SQL 语法创建文档数据库并进行查询 。Select Core (SQL) to create a document database and query by using SQL syntax.

    API 确定要创建的帐户的类型。The API determines the type of account to create. Azure Cosmos DB 提供五种 API:适用于文档数据的 Core (SQL) 和 MongoDB、适用于图形数据的 Gremlin、Azure 表和 Cassandra。Azure Cosmos DB provides five APIs: Core (SQL) and MongoDB for document data, Gremlin for graph data, Azure Table, and Cassandra. 目前,你必须为每种 API 创建单独的帐户。Currently, you must create a separate account for each API.

    详细了解 SQL APILearn more about the SQL API.
    LocationLocation 离用户最近的区域The region closest to your users 选择用于托管 Azure Cosmos DB 帐户的地理位置。Select a geographic location to host your Azure Cosmos DB account. 使用离用户最近的位置,使他们能够以最快的速度访问数据。Use the location that is closest to your users to give them the fastest access to the data.

    Azure Cosmos DB 的“新建帐户”页

  4. 选择“查看 + 创建” 。Select Review + create. 可以跳过“网络”和“标记”部分 。You can skip the Network and Tags sections.

  5. 检查帐户设置,然后选择“创建”。 Review the account settings, and then select Create. 创建帐户需要几分钟时间。It takes a few minutes to create the account. 等待门户页显示“你的部署已完成” 消息。Wait for the portal page to display Your deployment is complete.

    Azure 门户“通知”窗格

  6. 选择“转到资源”,转到 Azure Cosmos DB 帐户页。 Select Go to resource to go to the Azure Cosmos DB account page.

    Azure Cosmos DB 帐户页

步骤 2:设置 Visual Studio 项目Step 2: Set up your Visual Studio project

  1. 打开 Visual Studio 并选择“创建新项目” 。Open Visual Studio and select Create a new project.

  2. 在“创建新项目” 中,选择用于 C# 的“控制台应用(.NET Framework)” ,然后选择“下一步” 。In Create a new project, choose Console App (.NET Framework) for C#, then select Next.

  3. 将项目命名为 CosmosGettingStartedTutorial,然后选择“创建”。 Name your project CosmosGettingStartedTutorial, and then select Create.

    配置项目

  4. 在“解决方案资源管理器” 中,右键单击 Visual Studio 解决方案下方的新控制台应用程序,然后选择“管理 NuGet 包”。 In the Solution Explorer, right-click your new console application, which is under your Visual Studio solution, and select Manage NuGet Packages.

  5. 在“NuGet 包管理器” 中选择“浏览” ,然后搜索“Microsoft.Azure.Cosmos” 。In the NuGet Package Manager, select Browse and search for Microsoft.Azure.Cosmos. 选择“Microsoft.Azure.Cosmos” ,然后选择“安装” 。Choose Microsoft.Azure.Cosmos and select Install.

    安装用于 Azure Cosmos DB 客户端 SDK 的 NuGet

    Azure Cosmos DB SQL API 客户端库的包 ID 是 Azure Cosmos DB 客户端库The package ID for the Azure Cosmos DB SQL API Client Library is Azure Cosmos DB Client Library.

很好!Great! 现在,我们已完成安装,让我们开始编写一些代码。Now that we finished the setup, let's start writing some code. 如需本教程的已完成的项目,请参阅 Developing a .NET console app using Azure Cosmos DB(使用 Azure Cosmos DB 开发 .NET 控制台应用)。For the completed project of this tutorial, see Developing a .NET console app using Azure Cosmos DB.

步骤 3:连接到 Azure Cosmos DB 帐户Step 3: Connect to an Azure Cosmos DB account

  1. Program.cs 文件中 C# 应用程序开头的引用替换为以下引用:Replace the references at the beginning of your C# application in the Program.cs file with these references:

    using System;
    using System.Threading.Tasks;
    using System.Configuration;
    using System.Collections.Generic;
    using System.Net;
    using Microsoft.Azure.Cosmos;
    
  2. 将这些常量和变量添加到 Program 类中。Add these constants and variables into your Program class.

    public class Program
    {
        // ADD THIS PART TO YOUR CODE
    
        // The Azure Cosmos DB endpoint for running this sample.
        private static readonly string EndpointUri = "<your endpoint here>";
        // The primary key for the Azure Cosmos account.
        private static readonly string PrimaryKey = "<your primary key>";
    
        // 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";
    }
    

    Note

    如果你熟悉旧版 .NET SDK,则可能熟悉术语“集合”和“文档”。 If you're familiar with the previous version of the .NET SDK, you may be familiar with the terms collection and document. 由于 Azure Cosmos DB 支持多个 API 模型,因此 3.0 版的 .NET SDK 使用通用术语“容器”和“项”。 Because Azure Cosmos DB supports multiple API models, version 3.0 of the .NET SDK uses the generic terms container and item. 容器可以是集合、图或表。 A container can be a collection, graph, or table. 项可以是文档、边缘/顶点或行,是容器中的内容。 An item can be a document, edge/vertex, or row, and is the content inside a container. 有关详细信息,请参阅在 Azure Cosmos DB 中使用数据库、容器和项For more information, see Work with databases, containers, and items in Azure Cosmos DB.

  3. 打开 Azure 门户Open the Azure portal. 找到 Azure Cosmos DB 帐户,然后选择“密钥”。 Find your Azure Cosmos DB account, and then select Keys.

    从 Azure 门户获取 Azure Cosmos DB 密钥

  4. Program.cs 中,将 <your endpoint URL> 替换为 URI 的值。In Program.cs, replace <your endpoint URL> with the value of URI. <your primary key> 替换为“主密钥” 的值。Replace <your primary key> with the value of PRIMARY KEY.

  5. Main 方法下面,添加名为 GetStartedDemoAsync 的新异步任务,将新的 CosmosClient 实例化。Below the Main method, add a new asynchronous task called GetStartedDemoAsync, which instantiates our new CosmosClient.

    public static async Task Main(string[] args)
    {
    }
    
    // ADD THIS PART TO YOUR CODE
    /*
        Entry point to call methods that operate on Azure Cosmos DB resources in this sample
    */
    public async Task GetStartedDemoAsync()
    {
        // Create a new instance of the Cosmos Client
        this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
    }
    

    我们使用 GetStartedDemoAsync 作为入口点,该入口点调用在 Azure Cosmos DB 资源上运行的方法。We use GetStartedDemoAsync as the entry point that calls methods that operate on Azure Cosmos DB resources.

  6. 添加以下代码,从 Main 方法中运行 GetStartedDemoAsync 异步任务。Add the following code to run the GetStartedDemoAsync asynchronous task from your Main method. Main 方法将捕获异常并将它们写到控制台上。The Main method catches exceptions and writes them to the console.

    
    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();
        }
    }
    
    
  7. 选择 F5 来运行应用程序。Select F5 to run your application.

    控制台会显示消息“演示结束,请按任意键退出”。 The console displays the message: End of demo, press any key to exit. 此消息确认应用程序已连接到 Azure Cosmos DB。This message confirms that your application made a connection to Azure Cosmos DB. 然后,可以关闭控制台窗口。You can then close the console window.

祝贺!Congratulations! 你已成功连接到 Azure Cosmos DB 帐户。You've successfully connected to an Azure Cosmos DB account.

步骤 4:创建数据库Step 4: Create a database

数据库是跨容器分区的项的逻辑容器。A database is the logical container of items partitioned across containers. CosmosClient 类的 CreateDatabaseIfNotExistsAsyncCreateDatabaseAsync 方法可以创建数据库。Either the CreateDatabaseIfNotExistsAsync or CreateDatabaseAsync method of the CosmosClient class can create a database.

  1. 复制 CreateDatabaseAsync 方法并将其粘贴到 GetStartedDemoAsync 方法下面。Copy and paste the CreateDatabaseAsync method below your GetStartedDemoAsync method.

    
    /// <summary>
    /// Create the database if it does not exist
    /// </summary>
    private async Task CreateDatabaseAsync()
    {
        // Create a new database
        this.database = await this.cosmosClient.CreateDatabaseIfNotExistsAsync(databaseId);
        Console.WriteLine("Created Database: {0}\n", this.database.Id);
    }
    
    

    CreateDatabaseAsync 使用 databaseId 字段中指定的 ID FamilyDatabase 来创建新数据库(如果尚不存在该数据库)。CreateDatabaseAsync creates a new database with ID FamilyDatabase if it doesn't already exist, that has the ID specified from the databaseId field.

  2. 复制并粘贴以下代码,在其中实例化 CosmosClient 来调用刚添加的 CreateDatabaseAsync 方法。Copy and paste the code below where you instantiate the CosmosClient to call the CreateDatabaseAsync method you just added.

    public async Task GetStartedDemoAsync()
    {
        // Create a new instance of the Cosmos Client
        this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
    
        //ADD THIS PART TO YOUR CODE
        await this.CreateDatabaseAsync();
    }
    

    Program.cs 现在应如下所示,其中填充了终结点和主密钥。Your Program.cs should now look like this, with your endpoint and primary key filled in.

    using System;
    using System.Threading.Tasks;
    using System.Configuration;
    using System.Collections.Generic;
    using System.Net;
    using Microsoft.Azure.Cosmos;
    
    namespace CosmosGettingStartedTutorial
    {
        class Program
        {
            // The Azure Cosmos DB endpoint for running this sample.
            private static readonly string EndpointUri = "<your endpoint here>";
            // The primary key for the Azure Cosmos account.
            private static readonly string PrimaryKey = "<your primary key>";
    
            // 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...");
                    Program p = new Program();
                    await p.GetStartedDemoAsync();
                }
                catch (CosmosException de)
                {
                    Exception baseException = de.GetBaseException();
                    Console.WriteLine("{0} error occurred: {1}\n", de.StatusCode, de);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error: {0}\n", e);
                }
                finally
                {
                    Console.WriteLine("End of demo, press any key to exit.");
                    Console.ReadKey();
                }
            }
    
            /// <summary>
            /// Entry point to call methods that operate on Azure Cosmos DB resources in this sample
            /// </summary>
            public async Task GetStartedDemoAsync()
            {
                // Create a new instance of the Cosmos Client
                this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
                await this.CreateDatabaseAsync();
            }
    
            /// <summary>
            /// Create the database if it does not exist
            /// </summary>
            private async Task CreateDatabaseAsync()
            {
                // Create a new database
                this.database = await this.cosmosClient.CreateDatabaseIfNotExistsAsync(databaseId);
                Console.WriteLine("Created Database: {0}\n", this.database.Id);
            }
        }
    }
    
  3. 选择 F5 来运行应用程序。Select F5 to run your application.

祝贺!Congratulations! 你已成功创建 Azure Cosmos 数据库。You've successfully created an Azure Cosmos database.

步骤 5:创建容器Step 5: Create a container

Warning

方法 CreateContainerIfNotExistsAsync 创建新的容器,牵涉到定价。The method CreateContainerIfNotExistsAsync creates a new container, which has pricing implications. 有关详细信息,请访问 定价页For more details, please visit our pricing page.

可以使用 CosmosDatabase 类中的 CreateContainerIfNotExistsAsyncCreateContainerAsync 方法创建容器。A container can be created by using either the CreateContainerIfNotExistsAsync or CreateContainerAsync method in the CosmosDatabase class. 容器包含项(在使用 SQL API 的情况下为 JSON 文档)和关联的 JavaScript 服务器端应用程序逻辑,例如存储过程、用户定义的函数以及触发器。A container consists of items (JSON documents if SQL API) and associated server-side application logic in JavaScript, for example, stored procedures, user-defined functions, and triggers.

  1. 复制 CreateContainerAsync 方法并将其粘贴到 CreateDatabaseAsync 方法下面。Copy and paste the CreateContainerAsync method below your CreateDatabaseAsync method. CreateContainerAsync 使用 containerId 字段中指定的 ID FamilyContainer 来创建按 LastName 属性分区的新容器(如果尚不存在该容器)。CreateContainerAsync creates a new container with the ID FamilyContainer if it doesn't already exist, by using the ID specified from the containerId field partitioned by LastName property.

    
    /// <summary>
    /// 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.
    /// </summary>
    /// <returns></returns>
    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);
    }
    
    
  2. 复制并粘贴以下代码,其中实例化了 CosmosClient 来调用刚添加的 CreateContainer 方法。Copy and paste the code below where you instantiated the CosmosClient to call the CreateContainer method you just added.

    public async Task GetStartedDemoAsync()
    {
        // Create a new instance of the Cosmos Client
        this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
        await this.CreateDatabaseAsync();
    
        //ADD THIS PART TO YOUR CODE
        await this.CreateContainerAsync();
    }
    
  3. 选择 F5 来运行应用程序。Select F5 to run your application.

祝贺!Congratulations! 你已成功创建 Azure Cosmos 容器。You've successfully created an Azure Cosmos container.

步骤 6:向容器添加项Step 6: Add items to the container

CosmosContainer 类的 CreateItemAsync 方法可以创建项。The CreateItemAsync method of the CosmosContainer class can create an item. 使用 SQL API 时,项会投射为文档,后者是用户定义的任意 JSON 内容。When using the SQL API, items are projected as documents, which are user-defined arbitrary JSON content. 现在,可以将项插入 Azure Cosmos 容器中。You can now insert an item into your Azure Cosmos container.

在此示例中,让我们首先创建 Family 类来表示存储在 Azure Cosmos DB 中的对象。First, let's create a Family class that represents objects stored within Azure Cosmos DB in this sample. 我们还会创建在 Family 中使用的 ParentChildPetAddress 子类。We'll also create Parent, Child, Pet, Address subclasses that are used within Family. 该项必须有一个以 JSON 格式序列化为 idId 属性。The item must have an Id property serialized as id in JSON.

  1. 选择 Ctrl+Shift+A,打开“添加新项” 。Select Ctrl+Shift+A to open Add New Item. 将新类 Family.cs 添加到项目。Add a new class Family.cs to your project.

    向项目添加新的 Family.cs 类的屏幕截图

  2. 复制 FamilyParentChildPetAddress 类并将其粘贴到 Family.cs 中。Copy and paste the Family, Parent, Child, Pet, and Address class into Family.cs.

    using Newtonsoft.Json;
    
    namespace CosmosGettingStartedTutorial
    {
        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; }
        }
    }
    
    
  3. 回到 Program.cs 中,将 AddItemsToContainerAsync 方法添加到 CreateContainerAsync 方法后面。Back in Program.cs, add the AddItemsToContainerAsync method after your CreateContainerAsync method.

    
    /// <summary>
    /// Add Family items to the container
    /// </summary>
    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
        };
    
        try
        {
            // Read the item to see if it exists.  
            ItemResponse<Family> andersenFamilyResponse = await this.container.ReadItemAsync<Family>(andersenFamily.Id, new PartitionKey(andersenFamily.LastName));
            Console.WriteLine("Item in database with id: {0} already exists\n", andersenFamilyResponse.Resource.Id);
        }
        catch(CosmosException ex) when (ex.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"
            ItemResponse<Family> 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);
        }
    
        // Create a family object for the Wakefield family
        Family wakefieldFamily = new Family
        {
            Id = "Wakefield.7",
            LastName = "Wakefield",
            Parents = new Parent[]
            {
                new Parent { FamilyName = "Wakefield", FirstName = "Robin" },
                new Parent { FamilyName = "Miller", FirstName = "Ben" }
            },
            Children = new Child[]
            {
                new Child
                {
                    FamilyName = "Merriam",
                    FirstName = "Jesse",
                    Gender = "female",
                    Grade = 8,
                    Pets = new Pet[]
                    {
                        new Pet { GivenName = "Goofy" },
                        new Pet { GivenName = "Shadow" }
                    }
                },
                new Child
                {
                    FamilyName = "Miller",
                    FirstName = "Lisa",
                    Gender = "female",
                    Grade = 1
                }
            },
            Address = new Address { State = "NY", County = "Manhattan", City = "NY" },
            IsRegistered = true
        };
    
        try
        {
            // Read the item to see if it exists
            ItemResponse<Family> wakefieldFamilyResponse = await this.container.ReadItemAsync<Family>(wakefieldFamily.Id, new PartitionKey(wakefieldFamily.LastName));
            Console.WriteLine("Item in database with id: {0} already exists\n", wakefieldFamilyResponse.Resource.Id);
        }
        catch(CosmosException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
        {
            // Create an item in the container representing the Wakefield family. Note we provide the value of the partition key for this item, which is "Wakefield"
            ItemResponse<Family> wakefieldFamilyResponse = await this.container.CreateItemAsync<Family>(wakefieldFamily, new PartitionKey(wakefieldFamily.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", wakefieldFamilyResponse.Resource.Id, wakefieldFamilyResponse.RequestCharge);
        }
    }
    
    

    代码会进行检查,确保不存在 ID 相同的项。The code checks to make sure an item with the same ID doesn't already exist. 我们会插入两个项,Andersen 家族和 Wakefield 家族各一个。 We'll insert two items, one each for the Andersen Family and the Wakefield Family.

  4. GetStartedDemoAsync 方法中添加对 AddItemsToContainerAsync 的调用。Add a call to AddItemsToContainerAsync in the GetStartedDemoAsync method.

    public async Task GetStartedDemoAsync()
    {
        // Create a new instance of the Cosmos Client
        this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
        await this.CreateDatabaseAsync();
        await this.CreateContainerAsync();
    
        //ADD THIS PART TO YOUR CODE
        await this.AddItemsToContainerAsync();
    }
    
  5. 选择 F5 来运行应用程序。Select F5 to run your application.

祝贺!Congratulations! 你已成功创建两个 Azure Cosmos 项。You've successfully created two Azure Cosmos items.

步骤 7:查询 Azure Cosmos DB 资源Step 7: Query Azure Cosmos DB resources

Azure Cosmos DB 支持对存储在每个容器中的 JSON 文档进行各种查询。Azure Cosmos DB supports rich queries against JSON documents stored in each container. 有关详细信息,请参阅 SQL 查询入门For more information, see Getting started with SQL queries. 以下示例代码演示了如何针对我们在上一步插入的项来运行查询。The following sample code shows how to run a query against the items we inserted in the previous step.

  1. 复制 QueryItemsAsync 方法,并将其粘贴到 AddItemsToContainerAsync 方法后面。Copy and paste the QueryItemsAsync method after your AddItemsToContainerAsync method.

    
    /// <summary>
    /// Run a query (using Azure Cosmos DB SQL syntax) against the container
    /// </summary>
    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);
            }
        }
    }
    
    
  2. GetStartedDemoAsync 方法中添加对 QueryItemsAsync 的调用。Add a call to QueryItemsAsync in the GetStartedDemoAsync method.

    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();
    
        //ADD THIS PART TO YOUR CODE
        await this.QueryItemsAsync();
    }
    
  3. 选择 F5 来运行应用程序。Select F5 to run your application.

祝贺!Congratulations! 你已成功查询 Azure Cosmos 容器。You've successfully queried an Azure Cosmos container.

步骤 8:替换 JSON 项Step 8: Replace a JSON item

现在,我们将更新 Azure Cosmos DB 中的一个项。Now, we'll update an item in Azure Cosmos DB. 我们将更改 FamilyIsRegistered 属性以及某个孩子的 GradeWe'll change the IsRegistered property of the Family and the Grade of one of the children.

  1. 复制 ReplaceFamilyItemAsync 方法,并将其粘贴到 QueryItemsAsync 方法后面。Copy and paste the ReplaceFamilyItemAsync method after your QueryItemsAsync method.

    
    /// <summary>
    /// Replace an item in the container
    /// </summary>
    private async Task ReplaceFamilyItemAsync()
    {
        ItemResponse<Family> wakefieldFamilyResponse = await this.container.ReadItemAsync<Family>("Wakefield.7", new PartitionKey("Wakefield"));
        var itemBody = wakefieldFamilyResponse.Resource;
    
        // update registration status from false to true
        itemBody.IsRegistered = true;
        // update grade of child
        itemBody.Children[0].Grade = 6;
    
        // replace the item with the updated content
        wakefieldFamilyResponse = await this.container.ReplaceItemAsync<Family>(itemBody, itemBody.Id, new PartitionKey(itemBody.LastName));
        Console.WriteLine("Updated Family [{0},{1}].\n \tBody is now: {2}\n", itemBody.LastName, itemBody.Id, wakefieldFamilyResponse.Resource);
    }
    
    
  2. GetStartedDemoAsync 方法中添加对 ReplaceFamilyItemAsync 的调用。Add a call to ReplaceFamilyItemAsync in the GetStartedDemoAsync method.

    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();
    
        //ADD THIS PART TO YOUR CODE
        await this.ReplaceFamilyItemAsync();
    }
    
  3. 选择 F5 来运行应用程序。Select F5 to run your application.

祝贺!Congratulations! 你已成功替换 Azure Cosmos 项。You've successfully replaced an Azure Cosmos item.

步骤 9:删除项目Step 9: Delete item

现在,我们将删除 Azure Cosmos DB 中的一个项。Now, we'll delete an item in Azure Cosmos DB.

  1. 复制 DeleteFamilyItemAsync 方法,并将其粘贴到 ReplaceFamilyItemAsync 方法后面。Copy and paste the DeleteFamilyItemAsync method after your ReplaceFamilyItemAsync method.

    
    /// <summary>
    /// Delete an item in the container
    /// </summary>
    private async Task DeleteFamilyItemAsync()
    {
        var partitionKeyValue = "Wakefield";
        var familyId = "Wakefield.7";
    
        // Delete an item. Note we must provide the partition key value and id of the item to delete
        ItemResponse<Family> wakefieldFamilyResponse = await this.container.DeleteItemAsync<Family>(familyId,new PartitionKey(partitionKeyValue));
        Console.WriteLine("Deleted Family [{0},{1}]\n", partitionKeyValue, familyId);
    }
    
    
  2. GetStartedDemoAsync 方法中添加对 DeleteFamilyItemAsync 的调用。Add a call to DeleteFamilyItemAsync in the GetStartedDemoAsync method.

    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();
    
        //ADD THIS PART TO YOUR CODE
        await this.DeleteFamilyItemAsync();
    }
    
  3. 选择 F5 来运行应用程序。Select F5 to run your application.

祝贺!Congratulations! 你已成功删除 Azure Cosmos 项。You've successfully deleted an Azure Cosmos item.

步骤 10:删除数据库Step 10: Delete the database

现在,我们将删除数据库。Now we'll delete our database. 删除已创建的数据库会删除该数据库及其所有子资源。Deleting the created database removes the database and all children resources. 这些资源包括容器、项、任何存储过程、用户定义的函数以及触发器。The resources include containers, items, and any stored procedures, user-defined functions, and triggers. 我们还释放 CosmosClient 实例。We also dispose of the CosmosClient instance.

  1. 复制 DeleteDatabaseAndCleanupAsync 方法,并将其粘贴到 DeleteFamilyItemAsync 方法后面。Copy and paste the DeleteDatabaseAndCleanupAsync method after your DeleteFamilyItemAsync method.

    
    /// <summary>
    /// Delete the database and dispose of the Cosmos Client instance
    /// </summary>
    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();
    }
    
    
  2. GetStartedDemoAsync 方法中添加对 DeleteDatabaseAndCleanupAsync 的调用。Add a call to DeleteDatabaseAndCleanupAsync in the GetStartedDemoAsync method.

    
    /// <summary>
    /// Entry point to call methods that operate on Azure Cosmos DB resources in this sample
    /// </summary>
    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();
    }
    
    
  3. 选择 F5 来运行应用程序。Select F5 to run your application.

祝贺!Congratulations! 你已成功删除 Azure Cosmos 数据库。You've successfully deleted an Azure Cosmos database.

步骤 11:一起运行 C# 控制台应用程序!Step 11: Run your C# console application all together!

在 Visual Studio 中选择 F5,即可在调试模式下生成并运行应用程序。Select F5 in Visual Studio to build and run the application in debug mode.

应会在控制台窗口中看到整个应用的输出。You should see the output of your entire app in a console window. 输出会显示我们添加的查询的结果,The output shows the results of the queries we added. 并且应与下面的示例文本相符。It should match the example text below.

Beginning operations...

Created Database: FamilyDatabase

Created Container: FamilyContainer

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

Created item in database with id: Wakefield.7 Operation consumed 14.29 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}

Updated Family [Wakefield,Wakefield.7].
        Body is now: {"id":"Wakefield.7","LastName":"Wakefield","Parents":[{"FamilyName":"Wakefield","FirstName":"Robin"},{"FamilyName":"Miller","FirstName":"Ben"}],"Children":[{"FamilyName":"Merriam","FirstName":"Jesse","Gender":"female","Grade":6,"Pets":[{"GivenName":"Goofy"},{"GivenName":"Shadow"}]},{"FamilyName":"Miller","FirstName":"Lisa","Gender":"female","Grade":1,"Pets":null}],"Address":{"State":"NY","County":"Manhattan","City":"NY"},"IsRegistered":true}

Deleted Family [Wakefield,Wakefield.7]

Deleted Database: FamilyDatabase

End of demo, press any key to exit.

祝贺!Congratulations! 已经完成了本教程,并且获得了一个正常工作的 C# 控制台应用程序!You've completed the tutorial and have a working C# console application!

获取完整的教程解决方案Get the complete tutorial solution

如果没有时间完成本教程中的步骤,或者只需下载代码示例,则可下载这些示例。If you didn't have time to complete the steps in this tutorial, or just want to download the code samples, you can download it.

若要生成 GetStarted 解决方案,需要具备以下先决条件:To build the GetStarted solution, you need the following prerequisites:

若要在 Visual Studio 中还原对 Azure Cosmos DB .NET SDK 的引用,请在解决方案资源管理器中右键单击此解决方案,然后选择“还原 NuGet 包” 。To restore the references to the Azure Cosmos DB .NET SDK in Visual Studio, right-click the solution in Solution Explorer, and then select Restore NuGet Packages. 接下来,在 App.config 文件中更新 EndPointUriPrimaryKey 值,如步骤 3:连接到 Azure Cosmos DB 帐户所述。Next, in the App.config file, update the EndPointUri and PrimaryKey values as described in Step 3: Connect to an Azure Cosmos DB account.

就这么简单,生成以后即可开始操作!That's it, build it, and you're on your way!

后续步骤Next steps