生成一个用于在 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 you complete this tutorial, you'll have a console app that creates and queries Azure Cosmos DB resources.

本教程演示如何:This tutorial shows you how to:

  • 创建并连接到 Azure Cosmos DB 帐户Create an Azure Cosmos DB account and connect to it
  • 配置 Visual Studio 解决方案Configure a Visual Studio solution
  • 创建数据库Create a database
  • 创建集合Create a collection
  • 创建 JSON 文档Create JSON documents
  • 查询集合Query the collection
  • 更新 JSON 文档Update a JSON document
  • 删除文档Delete a document
  • 删除数据库Delete the database

先决条件Prerequisites

已安装包含 Azure 开发工作流的 Visual Studio 2017:Visual Studio 2017 with the Azure development workflow installed:

Azure 订阅,或免费的 Cosmos DB 试用帐户:An Azure subscription or free Cosmos DB trial account:

获取已完成的解决方案Get the completed solution

如果没有时间完成本教程,或者只想下载代码示例,则可从 GitHub 下载完整的解决方案。If you don't have time to complete the tutorial, or just want the code samples, you can download the complete solution from GitHub.

运行已下载的完整解决方案:To run the downloaded complete solution:

  1. 请确保已安装必备项Make sure you have the Prerequisites installed.
  2. 在 Visual Studio 中打开下载的 GetStarted.sln 解决方案文件 。Open the downloaded GetStarted.sln solution file in Visual Studio.
  3. 在“解决方案资源管理器”中,右键单击 GetStarted 项目,然后选择“管理 NuGet 包” 。In Solution Explorer, right-click the GetStarted project, and select Manage NuGet Packages.
  4. 在“NuGet”选项卡上,选择“还原”,以还原对 Azure Cosmos DB .NET SDK 的引用 。On the NuGet tab, select Restore to restore the references to the Azure Cosmos DB .NET SDK.
  5. 在 App.config 文件中,按照连接到 Azure Cosmos DB 帐户部分中的说明更新 EndpointUrlPrimaryKey 值 。In the App.config file, update the EndpointUrl and PrimaryKey values as described in the Connect to the Azure Cosmos DB account section.
  6. 选择“调试” > “开始执行(不调试)”或按 Ctrl+F5 生成并运行应用 。Select Debug > Start Without Debugging or press Ctrl+F5 to build and run the app.

创建 Azure Cosmos DB 帐户Create an Azure Cosmos DB account

按照以下说明在 Azure 门户中创建 Azure Cosmos DB 帐户。Follow these instructions to create an Azure Cosmos DB account in the Azure portal. 如果已有一个要使用的 Azure Cosmos DB 帐户,可直接跳到设置 Visual Studio 解决方案If you already have an Azure Cosmos DB account to use, skip ahead to Set up the Visual Studio solution.

  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 输入唯一的名称Enter 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 Core (SQL)Core (SQL) 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.

    选择“Core (SQL)”,以便使用 SQL 语法创建文档数据库并进行查询。Select Core (SQL) to create a document database and query by using SQL syntax.

    详细了解 SQL APILearn more about the SQL API.
    位置Location 选择离用户最近的区域Select 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 帐户页

设置 Visual Studio 解决方案Set up the Visual Studio solution

  1. 在 Visual Studio 2017 中,选择“文件” > “新建” > “项目” 。In Visual Studio 2017, select File > New > Project.

  2. 在“新建项目”对话框中,选择“Visual C#” > “控制台应用(.NET Framework)”,将项目命名为 AzureCosmosDBApp,然后选择“确定” 。In the New Project dialog, select Visual C# > Console App (.NET Framework), name your project AzureCosmosDBApp, and then select OK.

    “新建项目”窗口的屏幕截图

  3. 在“解决方案资源管理器”中,右键单击 AzureCosmosDBApp 项目,然后选择“管理 NuGet 包” 。In Solution Explorer, right-click the AzureCosmosDBApp project and select Manage NuGet Packages.

    项目上下文菜单

  4. 在“NuGet”选项卡上,选择“浏览”,并在搜索框中输入 azure documentdb 。On the NuGet tab, select Browse, and enter azure documentdb in the search box.

  5. 找到并选择 Microsoft.Azure.DocumentDB,然后选择“安装”(如果尚未安装) 。Find and select Microsoft.Azure.DocumentDB, and select Install if it's not already installed.

    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.

    Note

    若正使用 .NET Core,请参阅 .NET Core 文档If you are using .NET Core, please see the .NET Core docs.

    用于查找 Azure Cosmos DB 客户端 SDK 的 NuGet 菜单的屏幕截图

    如果收到有关预览解决方案更改的消息,请选择“确定” 。If you get a message about previewing changes to the solution, select OK. 如果收到有关接受许可证的消息,请选择“我接受” 。If you get a message about license acceptance, select I accept.

连接到 Azure Cosmos DB 帐户Connect to the Azure Cosmos DB account

现可开始编写代码。Now, get started writing some code. 本教程的完整 Project.cs 文件位于 GitHub 中 。The complete Project.cs file for this tutorial is in GitHub.

  1. 在“解决方案资源管理器”中,选择“Program.cs”,然后在代码编辑器中,将以下引用添加到文件的开头 :In Solution Explorer, select Program.cs, and in the code editor, add the following references to the beginning of the file:

    using System.Net;
    using Microsoft.Azure.Documents;
    using Microsoft.Azure.Documents.Client;
    using Newtonsoft.Json;
    
  2. 接下来,将以下两个常量和 client 变量添加到 public class ProgramNext, add the following two constants and the client variable to public class Program.

    
    public class Program
    {
      private const string EndpointUrl = "<your endpoint URL>";
      private const string PrimaryKey = "<your primary key>";
      private DocumentClient client;
    
  3. 终结点 URL 和主密钥让应用可以连接到 Azure Cosmos DB 帐户,并让 Azure Cosmos DB 帐户信任该连接。The endpoint URL and primary key allow your app to connect to your Azure Cosmos DB account, and the Azure Cosmos DB account to trust the connection. Azure 门户复制密钥,并将其粘贴到代码中。Copy the keys from the Azure portal, and paste them into your code.

    1. 在 Azure Cosmos DB 帐户的左侧导航栏中,选择“密钥”。 In your Azure Cosmos DB account left navigation, select Keys.

      在 Azure 门户中查看并复制访问密钥

    2. 在“读/写密钥”下,使用右侧的复制按钮复制“URI”值,并将其粘贴到 Program.cs 的 <your endpoint URL> 中 。Under Read-write Keys, copy the URI value using the copy button at the right, and paste it into <your endpoint URL> in Program.cs. 例如:For example:

      private const string EndpointUrl = "https://mysqlapicosmosdb.documents.azure.cn:443/";

    3. 复制“主密钥”值,并将其粘贴到 Program.cs 的 <your primary key> 中 。Copy the PRIMARY KEY value and paste it into <your primary key> in Program.cs. 例如:For example:

      private const string PrimaryKey = "19ZDNJAiYL26tmnRvoez6hmtIfBGwjun50PWRjNYMC2ig8Ob9hYk7Fq1RYSv8FcIYnh1TdBISvCh7s6yyb0000==";

  4. Main 方法之后,添加一个名为 GetStartedDemo 的新异步任务,用来实例化名为 client 的新 DocumentClientAfter the Main method, add a new asynchronous task called GetStartedDemo, which instantiates a new DocumentClient called client.

    private async Task GetStartedDemo()
    {
        client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey);
    }
    
  5. 将以下代码添加到 Main 方法中,以运行 GetStartedDemo 任务。Add the following code to the Main method to run the GetStartedDemo task. Main 方法可捕获异常并将它们写入控制台。The Main method catches exceptions and writes them to the console.

    static void Main(string[] args)
    {
        try
        {
           Program p = new Program();
           p.GetStartedDemo().Wait();
        }
        catch (DocumentClientException de)
        {
           Exception baseException = de.GetBaseException();
           Console.WriteLine($"{de.StatusCode} error occurred: {de.Message}, Message: {baseException.Message}");
        }
        catch (Exception e)
        {
           Exception baseException = e.GetBaseException();
           Console.WriteLine($"Error: {e.Message}, Message: {baseException.Message}");
        }
        finally
        {
           Console.WriteLine("End of demo, press any key to exit.");
           Console.ReadKey();
        }
    }
    
  6. 按 F5 运行应用 。Press F5 to run your app.

  7. 如果控制台窗口中显示“演示结束,按任意键退出”消息,则表示连接成功 。When you see the message End of demo, press any key to exit in the console window, it means the connection was successful. 按任意键关闭控制台窗口。Press any key to close the console window.

已成功连接到 Azure Cosmos DB 帐户。You've successfully connected to your Azure Cosmos DB account. 现在,可使用某些 Azure Cosmos DB 资源。Now, work with some Azure Cosmos DB resources.

创建数据库Create a database

Azure Cosmos DB 数据库是跨集合分区的 JSON 文档存储的逻辑容器。An Azure Cosmos DB database is the logical container of JSON document storage partitioned across collections. 可使用 DocumentClient 类的 CreateDatabaseIfNotExistsAsync 方法创建数据库。You create a database by using the CreateDatabaseIfNotExistsAsync method of the DocumentClient class.

  1. 在添加创建数据库的代码之前,添加一个用于向控制台写入的帮助器方法。Before you add the code for creating a database, add a helper method for writing to the console. 复制以下 WriteToConsoleAndPromptToContinue 方法,并将其粘贴到代码中的 GetStartedDemo 方法之后。Copy and paste the following WriteToConsoleAndPromptToContinue method after the GetStartedDemo method in your code.

    private void WriteToConsoleAndPromptToContinue(string format, params object[] args)
    {
      Console.WriteLine(format, args);
      Console.WriteLine("Press any key to continue...");
      Console.ReadKey();
    }
    
  2. 复制以下行并将其粘贴到 GetStartedDemo 方法的 client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey); 行之后。Copy and paste the following line to your GetStartedDemo method, after the client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey); line. 此代码将创建一个名为 FamilyDB 的数据库。This code creates a database named FamilyDB.

    await client.CreateDatabaseIfNotExistsAsync(new Database { Id = "FamilyDB" });
    
  3. 按 F5 运行应用 。Press F5 to run your app.

已成功创建 Azure Cosmos DB 数据库。You've successfully created an Azure Cosmos DB database. 在 Azure Cosmos DB 帐户左侧导航中选择“数据资源管理器”,即可在 Azure 门户中查看数据库 。You can see the database in the Azure portal by selecting Data Explorer in your Azure Cosmos DB account left navigation.

创建集合Create a collection

集合是 JSON 文档和相关联的 JavaScript 应用程序逻辑的容器。A collection is a container of JSON documents and associated JavaScript application logic. 使用 DocumentClient 类的 CreateDocumentCollectionIfNotExistsAsync 方法可创建集合。You create a collection by using the CreateDocumentCollectionIfNotExistsAsync method of the DocumentClient class.

Important

CreateDocumentCollectionIfNotExistsAsync 可创建一个具有保留吞吐量的新集合,这种方式牵涉定价 。CreateDocumentCollectionIfNotExistsAsync creates a new collection with reserved throughput, which has pricing implications. 有关详细信息,请访问定价页For more details, visit the pricing page.

  1. 复制以下代码并将其粘贴到 GetStartedDemo 方法的 await client.CreateDatabaseIfNotExistsAsync(new Database { Id = "FamilyDB" }); 行之后。Copy and paste the following code to your GetStartedDemo method after the await client.CreateDatabaseIfNotExistsAsync(new Database { Id = "FamilyDB" }); line. 此代码会创建一个名为 FamilyCollection 的文档集合。This code creates a document collection named FamilyCollection.

    await client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("FamilyDB"), new DocumentCollection { Id = "FamilyCollection" });
    
  2. 按 F5 运行应用 。Press F5 to run your app.

已成功创建 Azure Cosmos DB 文档集合。You've successfully created an Azure Cosmos DB document collection. 在 Azure 门户中,可在“数据资源管理器”的“FamilyDB”数据库下看到该集合 。You can see the collection under your FamilyDB database in Data Explorer in the Azure portal.

创建 JSON 文档Create JSON documents

文档是用户定义的任意 JSON 内容。Documents are user-defined, arbitrary JSON content. 文档必须将 ID 属性序列化为 JSON 格式的 idDocuments must have an ID property serialized as id in JSON. 可使用 DocumentClient 类的 CreateDocumentAsync 方法创建文档。You create documents by using the CreateDocumentAsync method of the DocumentClient class.

Tip

如果已有要在数据库中存储的数据,则可以使用 Azure Cosmos DB 的数据迁移工具导入数据。If you already have data you'd like to store in your database, you can use the Azure Cosmos DB Data Migration tool to import it.

以下代码可创建两个文档并将其插入到数据库集合中。The following code creates and inserts two documents into your database collection. 首先,创建一个 Family 类,以及 ParentChildPetAddress 子类,以便在 Family 中使用。First, you create a Family class, and Parent, Child, Pet, and Address subclasses to use within Family. 然后,创建一个 CreateFamilyDocumentIfNotExists 方法,同时创建并插入两个文档。Then, you create a CreateFamilyDocumentIfNotExists method, and then create and insert two documents.

  1. 复制以下 FamilyParentChildPetAddress 类,并将其粘贴到代码中的 WriteToConsoleAndPromptToContinue 方法之后。Copy and paste the following Family, Parent, Child, Pet, and Address classes after the WriteToConsoleAndPromptToContinue method in your code.

    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; }
    }
    
  2. 复制以下 CreateFamilyDocumentIfNotExists 方法,并将其粘贴到刚刚添加的 Address 类之后。Copy and paste the following CreateFamilyDocumentIfNotExists method after the Address class you just added.

    private async Task CreateFamilyDocumentIfNotExists(string databaseName, string collectionName, Family family)
    {
        try
        {
            await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, family.Id));
            WriteToConsoleAndPromptToContinue($"Found {family.Id}");
        }
        catch (DocumentClientException de)
        {
            if (de.StatusCode == HttpStatusCode.NotFound)
            {
                await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), family);
                WriteToConsoleAndPromptToContinue($"Created Family {family.Id}");
            }
            else
            {
                throw;
            }
        }
    }
    
  3. 复制以下代码,并将其粘贴到 GetStartedDemo 方法末尾的 await client.CreateDocumentCollectionIfNotExistsAsync 行之后。Copy and paste the following code at the end of your GetStartedDemo method, after the await client.CreateDocumentCollectionIfNotExistsAsync line. 此代码创建并插入两个文档,分别用于 Andersen 和 Wakefield 系列。This code creates and inserts two documents, one each for the Andersen and Wakefield families.

    Family andersenFamily = new Family
    {
        Id = "AndersenFamily",
        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 = true
    };
    
    await CreateFamilyDocumentIfNotExists("FamilyDB", "FamilyCollection", andersenFamily);
    
    Family wakefieldFamily = new Family
    {
        Id = "WakefieldFamily",
        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 = false
    };
    
    await CreateFamilyDocumentIfNotExists("FamilyDB", "FamilyCollection", wakefieldFamily);
    
  4. 按 F5 运行应用 。Press F5 to run your app.

已成功创建两个 Azure Cosmos DB 文档。You've successfully created two Azure Cosmos DB documents. 在 Azure 门户中,可在“数据资源管理器”的“FamilyDB”数据库和“FamilyCollection”集合下看到这些文档 。You can see the documents under your FamilyDB database and FamilyCollection collection in Data Explorer in the Azure portal.

演示帐户、联机数据库、集合和文档之间的层次关系的示意图

查询 Azure Cosmos DB 资源Query Azure Cosmos DB resources

Azure Cosmos DB 支持对存储在集合中的 JSON 文档进行各种查询Azure Cosmos DB supports rich queries against JSON documents stored in collections. 以下示例代码使用 LINQ 和 Azure Cosmos DB SQL 语法对示例文档运行查询。The following sample code uses LINQ and Azure Cosmos DB SQL syntax to run a query against the sample documents.

  1. 复制以下 ExecuteSimpleQuery 方法,并将其粘贴到代码中的 CreateFamilyDocumentIfNotExists 方法之后。Copy and paste the following ExecuteSimpleQuery method after the CreateFamilyDocumentIfNotExists method in your code.

    private void ExecuteSimpleQuery(string databaseName, string collectionName)
    {
        // Set some common query options.
        FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1 };
    
        // Find the Andersen family by its LastName.
        IQueryable<Family> familyQuery = client.CreateDocumentQuery<Family>(
            UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), queryOptions)
            .Where(f => f.LastName == "Andersen");
    
        // Execute the query synchronously. 
        // You could also execute it asynchronously using the IDocumentQuery<T> interface.
        Console.WriteLine("Running LINQ query...");
        foreach (Family family in familyQuery)
        {
            Console.WriteLine($"\tRead {family}");
        }
    
        // Now execute the same query using direct SQL.
        IQueryable<Family> familyQueryInSql = client.CreateDocumentQuery<Family>(
            UriFactory.CreateDocumentCollectionUri(databaseName, collectionName),
            "SELECT * FROM Family WHERE Family.LastName = 'Andersen'",
            queryOptions);
    
        Console.WriteLine("Running direct SQL query...");
        foreach (Family family in familyQueryInSql)
        {
            Console.WriteLine($"\tRead {family}");
        }
    
        Console.WriteLine("Press any key to continue ...");
        Console.ReadKey();
    }
    
  2. 复制以下代码,并将其粘贴到 GetStartedDemo 方法末尾的 await CreateFamilyDocumentIfNotExists("FamilyDB", "FamilyCollection", wakefieldFamily); 行之后。Copy and paste the following code at the end of your GetStartedDemo method, after the await CreateFamilyDocumentIfNotExists("FamilyDB", "FamilyCollection", wakefieldFamily); line.

      ExecuteSimpleQuery("FamilyDB", "FamilyCollection");
    
  3. 按 F5 运行应用 。Press F5 to run your app.

前面的查询返回 Andersen 系列的完整项。The preceding query returns the complete item for the Andersen family. 已成功完成对 Azure Cosmos DB 集合的查询。You've successfully queried against an Azure Cosmos DB collection.

下图说明了如何针对集合调用 Azure Cosmos DB SQL 查询语法。The following diagram illustrates how the Azure Cosmos DB SQL query syntax calls against the collection. 同样的逻辑也适用于 LINQ 查询。The same logic applies to the LINQ query.

说明 NoSQL 教程创建 C# 控制台应用程序所用查询的范围和意义的图表

SQL 查询中的 FROM 关键字是可选项,因为 Azure Cosmos DB 查询已限制为单个集合。The FROM keyword in the SQL query is optional, because Azure Cosmos DB queries are already scoped to a single collection. 可将 FROM Families f 替换为 FROM root r 或所选的任何其他变量名称。You can swap FROM Families f with FROM root r, or any other variable name you choose. Azure Cosmos DB 将推断表示当前集合的所选 Familiesroot 或变量名。Azure Cosmos DB will infer that Families, root, or the variable name you choose refers to the current collection.

更新 JSON 文档Update a JSON document

Azure Cosmos DB SQL API 支持更新和替换 JSON 文档。Azure Cosmos DB SQL API supports updating and replacing JSON documents.

  1. 复制以下 ReplaceFamilyDocument 方法,并将其粘贴到代码中的 ExecuteSimpleQuery 方法之后。Copy and paste the following ReplaceFamilyDocument method after the ExecuteSimpleQuery method in your code.

    private async Task ReplaceFamilyDocument(string databaseName, string collectionName, string familyName, Family updatedFamily)
    {
       await client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, familyName), updatedFamily);
       WriteToConsoleAndPromptToContinue($"Replaced Family {familyName}");
    }
    
  2. 复制以下代码,并将其粘贴到 GetStartedDemo 方法末尾的 ExecuteSimpleQuery("FamilyDB", "FamilyCollection"); 行之后。Copy and paste the following code at the end of your GetStartedDemo method, after the ExecuteSimpleQuery("FamilyDB", "FamilyCollection"); line. 该代码更新其中一个文档中的数据,然后再次运行查询以显示已更改的文档。The code updates the data in one of the documents, and then runs the query again to show the changed document.

    // Update the Grade of the Andersen Family child
    andersenFamily.Children[0].Grade = 6;
    await ReplaceFamilyDocument("FamilyDB", "FamilyCollection", "AndersenFamily", andersenFamily);
    ExecuteSimpleQuery("FamilyDB", "FamilyCollection");
    
  3. 按 F5 运行应用 。Press F5 to run your app.

查询输出显示 Andersen Family 的子项 Grade5 更新为 6The query output shows that the Grade for the Andersen Family's child updated from 5 to 6. 已成功更新并替换 Azure Cosmos DB 文档。You've successfully updated and replaced an Azure Cosmos DB document.

删除 JSON 文档Delete a JSON document

Azure Cosmos DB SQL API 支持删除 JSON 文档。Azure Cosmos DB SQL API supports deleting JSON documents.

  1. 复制以下 DeleteFamilyDocument 方法,并将其粘贴到 ReplaceFamilyDocument 方法之后。Copy and paste the following DeleteFamilyDocument method after the ReplaceFamilyDocument method.

    private async Task DeleteFamilyDocument(string databaseName, string collectionName, string documentName)
    {
        await client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, documentName));
        Console.WriteLine($"Deleted Family {documentName}");
    }
    
  2. 复制以下代码,并将其粘贴到 GetStartedDemo 方法末尾的第二个 ExecuteSimpleQuery("FamilyDB", "FamilyCollection"); 行之后。Copy and paste the following code at the end of your GetStartedDemo method, after the second ExecuteSimpleQuery("FamilyDB", "FamilyCollection"); line.

    await DeleteFamilyDocument("FamilyDB", "FamilyCollection", "AndersenFamily");
    
  3. 按 F5 运行应用 。Press F5 to run your app.

已成功删除 Azure Cosmos DB 文档。You've successfully deleted an Azure Cosmos DB document.

删除数据库Delete the database

删除所创建的数据库,以将它及其所有子资源(包括集合和文档)删除。Delete the database you created to remove it and all its child resources, including the collection and documents.

  1. 复制以下代码,并将其粘贴到 GetStartedDemo 方法末尾的 await DeleteFamilyDocument("FamilyDB", "FamilyCollection", "AndersenFamily"); 行之后。Copy and paste the following code at the end of your GetStartedDemo method, after the await DeleteFamilyDocument("FamilyDB", "FamilyCollection", "AndersenFamily"); line.

    // Clean up - delete the database
    await client.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri("FamilyDB"));
    
  2. 按 F5 运行应用 。Press F5 to run your app.

已成功删除 Azure Cosmos DB 数据库。You've successfully deleted the Azure Cosmos DB database. 在“数据资源管理器”中,可看到 Azure Cosmos DB 帐户删除了 FamilyDB 数据库 。You can see in the Data Explorer for your Azure Cosmos DB account that the FamilyDB database is deleted.

运行整个 C# 控制台应用Run the entire C# console app

在 Visual Studio 中按 F5,即可在调试模式下生成并运行完整的 C# 控制台应用 。Press F5 in Visual Studio to build and run the complete C# console app in debug mode. 控制台窗口中应该会显示以下输出:You should see the following output in the console window:

Created Family AndersenFamily
Press any key to continue ...
 Created Family WakefieldFamily
Press any key to continue ...
 Running LINQ query...
        Read {"id":"AndersenFamily","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":true}
Running direct SQL query...
        Read {"id":"AndersenFamily","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":true}
Press any key to continue ...
 Replaced Family AndersenFamily
Press any key to continue ...
 Running LINQ query...
        Read {"id":"AndersenFamily","LastName":"Andersen","Parents":[{"FamilyName":null,"FirstName":"Thomas"},{"FamilyName":null,"FirstName":"Mary Kay"}],"Children":[{"FamilyName":null,"FirstName":"Henriette Thaulow","Gender":"female","Grade":6,"Pets":[{"GivenName":"Fluffy"}]}],"Address":{"State":"WA","County":"King","City":"Seattle"},"IsRegistered":true}
Running direct SQL query...
        Read {"id":"AndersenFamily","LastName":"Andersen","Parents":[{"FamilyName":null,"FirstName":"Thomas"},{"FamilyName":null,"FirstName":"Mary Kay"}],"Children":[{"FamilyName":null,"FirstName":"Henriette Thaulow","Gender":"female","Grade":6,"Pets":[{"GivenName":"Fluffy"}]}],"Address":{"State":"WA","County":"King","City":"Seattle"},"IsRegistered":true}
Press any key to continue ...
 Deleted Family AndersenFamily
End of demo, press any key to exit.

祝贺!Congratulations! 你已完成本教程,并拥有一个能够正常运行的 C# 控制台应用,可用于创建、查询、更新和删除 Azure Cosmos DB 资源。You've completed the tutorial, and have a working C# console app that creates, queries, updates, and deletes Azure Cosmos DB resources.

后续步骤Next steps