65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 .NET Core 控制台应用构建 Azure Cosmos DB SQL API 帐户的数据管理(SDK 版本 3 预览版)

starIconstarIconstarIconemptyStarIconemptyStarIcon

3.00/5 (4投票s)

2018年12月20日

CPOL
viewsIcon

10962

本教程介绍如何构建一个 .NET Core 应用程序来管理 Azure Cosmos DB SQL API 数据。

欢迎学习使用 .NET Core 进行 Azure Cosmos DB SQL API 入门教程!完成本教程后,您将拥有一个创建和查询 Azure Cosmos DB 资源的 .NET Core 控制台应用程序。本教程使用的是 Azure Cosmos DB .NET SDK 的 3.0+ 版本,它支持 .NET Standard 2.0

本教程涵盖

  • 创建 Azure Cosmos 帐户并连接
  • 在 Visual Studio 中配置项目
  • 创建数据库和容器
  • 向容器添加项
  • 查询容器
  • 对项执行 CRUD 操作
  • 删除数据库

没时间创建应用程序?别担心!完整的解决方案可在 GitHub 上获取。请跳转到 获取完整解决方案 部分以快速了解说明。

想使用 SQL API 和 .NET Core SDK 构建 Xamarin iOS、Android 或 Forms 应用程序?请参阅 使用 Xamarin 和 Azure Cosmos DB 构建移动应用程序

必备组件

  • 一个有效的 Azure 帐户。如果您还没有,可以注册一个免费帐户

    您可以免费试用 Azure Cosmos DB,无需 Azure 订阅,免费且无任何义务。或者,您可以使用Azure Cosmos DB 模拟器,其 URI 为 https://:8081。主密钥在 身份验证请求 中提供。

  • 如果您尚未安装 Visual Studio 2017,可以下载并使用免费的 Visual Studio 2017 社区版。如果您正在开发通用 Windows 平台 (UWP) 应用,则应使用15.4 或更高版本的 Visual Studio 2017。在 Visual Studio 设置过程中,请确保启用Azure 开发工作负载。

    • 如果您在 MacOS 或 Linux 上工作,可以通过安装适用于您所选平台的.NET Core SDK,从命令行开发 .NET Core 应用程序。

    • 如果您在 Windows 上工作,可以通过安装.NET Core SDK,从命令行开发 .NET Core 应用程序。

    • 您可以使用自己的编辑器,或下载免费的 Visual Studio Code,它适用于 Windows、Linux 和 MacOS。

步骤 1:创建 Azure Cosmos DB 帐户

让我们创建一个 Azure Cosmos DB 帐户。如果您已有一个要使用的帐户,可以跳至设置 Visual Studio 解决方案。如果您正在使用 Azure Cosmos DB 模拟器,请按照 Azure Cosmos DB 模拟器 中的步骤设置模拟器,然后跳至设置 Visual Studio 项目

  1. 在新浏览器窗口中,登录 Azure 门户
  2. 选择创建资源 > 数据库 > Azure Cosmos DB

  3. 创建 Azure Cosmos DB 帐户页面上,输入新的 Azure Cosmos DB 帐户的基本设置。

    设置 描述
    订阅 您的订阅 选择要用于此 Azure Cosmos DB 帐户的 Azure 订阅。
    资源组 新建

    然后输入与 ID 中提供的相同的唯一名称
    选择新建。然后为您的帐户输入新的资源组名称。为简单起见,请使用与您的 ID 相同的名称。
    科目名称 输入唯一名称 输入一个唯一名称来标识您的 Azure Cosmos DB 帐户。由于 documents.azure.com 会附加到您提供的 ID 以创建 URI,因此请使用唯一 ID。

    ID 只能包含小写字母、数字和连字符 (-) 字符。其长度必须在 3 到 31 个字符之间。
    API Core(SQL) API 决定要创建的帐户类型。Azure Cosmos DB 提供五种 API:用于文档数据库的 Core(SQL),用于图数据库的 Gremlin,用于文档数据库的 MongoDB,Azure Table 和 Cassandra。目前,您必须为每种 API 创建一个单独的帐户。

    选择Core(SQL),因为在本文中您将创建一个文档数据库并使用 SQL 语法进行查询。

    详细了解 SQL API.
    Location 选择离您的用户最近的区域 选择一个托管您的 Azure Cosmos DB 帐户的地理位置。使用离您的用户最近的位置,以便他们能最快地访问数据。

    选择审查+创建。您可以跳过网络标记部分。

  4. 帐户创建需要几分钟时间。等待门户显示恭喜!您的 Azure Cosmos DB 帐户已创建页面。

步骤 2:设置 Visual Studio 项目

  1. 在您的计算机上打开Visual Studio 2017
  2. 文件菜单上,选择新建,然后选择项目
  3. 新建项目对话框中,选择Visual C# / 控制台应用(.NET Core),为您的项目命名,然后单击确定

  4. 解决方案资源管理器中,右键单击您的新控制台应用程序(位于您的 Visual Studio 解决方案下),然后单击管理 NuGet 程序包...

  5. NuGet选项卡中,单击浏览,然后在搜索框中键入Microsoft.Azure.Cosmos

  6. 在结果中,找到Microsoft.Azure.Cosmos并单击安装。Azure Cosmos DB SQL API 客户端库的程序包 ID 为 Microsoft Azure Cosmos DB 客户端库

    如果您收到有关查看解决方案更改的消息,请单击确定。如果您收到有关接受许可证的消息,请单击我接受

太棒了!现在我们已经完成了设置,让我们开始编写代码。您可以在 GitHub 上找到本教程的完整代码项目。

步骤 3:连接到 Azure Cosmos DB 帐户

  1. 首先,将 C# 应用程序开头 `Program.cs` 文件中的引用替换为以下引用

    using System;
    using System.Threading.Tasks;
    using Microsoft.Azure.Cosmos;
    using System.Collections.Generic;
    using System.Net;
    
  2. 接下来,将这些常量和变量添加到您的公共类 `Program` 中。

    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 CosmosDatabase database;
    
        // The container we will create.
        private CosmosContainer container;
    
        // The name of the database and container we will create
        private string databaseId = "FamilyDatabase";
        private string containerId = "FamilyContainer";
    }
    

    请注意,如果您熟悉之前版本的 .NET SDK,您可能习惯使用“collection”和“document”这两个术语。由于 Azure Cosmos DB 支持多种 API 模型,因此 .NET SDK 3.0+ 版本使用通用的术语“container”(容器)和“item”(项)。容器可以是 collection、graph 或 table。项可以是 document、edge/vertex 或 row,并且是容器内的内容。详细了解数据库、容器和项。

  3. Azure 门户中检索您的终结点 URL 和主密钥。

    在 Azure 门户中,导航到您的 Azure Cosmos DB 帐户,然后单击密钥

    将门户中的 URI 复制并粘贴到 `Program.cs` 文件中的 `<your endpoint URL>`。复制门户中的 PRIMARY KEY 并将其粘贴到 `<your primary key>`。

  4. 接下来,我们将创建一个新的 `CosmosClient` 实例并为我们的程序设置一些框架。

    在 `Main` 方法下方,添加一个名为 `GetStartedDemoAsync` 的新异步任务,该任务将实例化我们新的 `CosmosClient`。我们将使用 `GetStartedDemoAsync` 作为调用操作 Azure Cosmos DB 资源的方法的入口点。

    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);
    }
    
  5. 将以下代码添加到您的 `Main` 方法中以运行 `GetStartedDemoAsync` 异步任务。`Main` 方法将捕获异常并将其写入控制台。

    public static async Task Main(string[] args)
    {
        // ADD THIS PART TO YOUR CODE
        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}\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();
        }
    }
    
  6. F5 运行您的应用程序。控制台窗口输出将显示消息“End of demo, press any key to exit.”,确认已建立到 Azure Cosmos DB 的连接。然后您可以关闭控制台窗口。

恭喜!您已成功连接到 Azure Cosmos DB 帐户。

步骤 4:创建数据库

`Databases` 类的 CreateDatabaseIfNotExistsAsyncCreateDatabaseAsync 函数都可以用于创建数据库。数据库是跨容器分区的项的逻辑容器。

  1. 将 `CreateDatabase` 方法复制并粘贴到您的 `GetStartedDemoAsync` 方法下方。`CreateDatabase` 将创建一个名为 `FamilyDatabase` 的新数据库(如果它尚不存在),其 ID 来自 `databaseId` 字段。

    /*
        Create the database if it does not exist
    */
    private async Task CreateDatabase()
    {
        // Create a new database
        this.database = await this.cosmosClient.Databases.CreateDatabaseIfNotExistsAsync(databaseId);
        Console.WriteLine("Created Database: {0}\n", this.database.Id);
    }
    
  2. 将代码复制并粘贴到您实例化 CosmosClient 的位置,以调用您刚刚添加的 `CreateDatabase` 方法。

    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.CreateDatabase();
    }
    

    此时,您的代码应如下所示,并填入了您的终结点和主密钥。请注意,您的命名空间将根据您的项目名称而有所不同。

    using System;
    using System.Threading.Tasks;
    using Microsoft.Azure.Cosmos;
    using System.Collections.Generic;
    using System.Net;
    
    namespace CosmosGettingStartedDotnetCoreTutorial
    {
        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 CosmosDatabase database;
    
            // The container we will create.
            private CosmosContainer 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();
                }
            }
    
            /*
                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);
                await this.CreateDatabase();
            }
    
            /*
                Create the database if it does not exist
            */
            private async Task CreateDatabase()
            {
                // Create a new database
                this.database = await this.cosmosClient.Databases.CreateDatabaseIfNotExistsAsync(databaseId);
                Console.WriteLine("Created Database: {0}\n", this.database.Id);
            }
        }
    }
    

F5 运行您的应用程序。

恭喜!您已成功创建了一个 Azure Cosmos DB 数据库。

步骤 5:创建容器

警告

调用 `CreateContainerIfNotExistsAsync` 方法将创建一个新容器,这会产生费用。有关更多详细信息,请访问我们的定价页面

`Containers` 类的 CreateContainerIfNotExistsAsyncCreateContainerAsync 函数都可以用于创建容器。容器包含项(在 SQL API 的情况下是 JSON 文档)以及相关的 JavaScript 服务器端应用程序逻辑,例如存储过程、用户定义函数和触发器。

  1. 将 `CreateContainer` 方法复制并粘贴到您的 `CreateDatabase` 方法下方。`CreateContainer` 将创建一个名为 `FamilyContainer` 的新容器(如果它尚不存在),其 ID 来自 `containerId` 字段。

    /*
        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 CreateContainer()
    {
        // Create a new container
        this.container = await this.database.Containers.CreateContainerIfNotExistsAsync(containerId, "/LastName");
        Console.WriteLine("Created Container: {0}\n", this.container.Id);
    }
    
  2. 将代码复制并粘贴到您实例化 `CosmosClient` 的位置,以调用您刚刚添加的 `CreateContainer` 方法。

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

F5 运行您的应用程序。

恭喜!您已成功创建了一个 Azure Cosmos DB 容器。

步骤 6:向容器添加项

可以使用 **Items** 类的 CreateItemAsync 函数创建项。在使用 SQL API 时,项被表示为文档,即用户定义(任意)的 JSON 内容。您现在可以将项插入到您的 Azure Cosmos DB 容器中。

首先,我们需要创建一个 `Family` 类来表示此示例中存储在 Azure Cosmos DB 中的对象。我们还将创建 `Parent`、`Child`、`Pet` 和 `Address` 子类,它们在 `Family` 中使用。请注意,文档必须有一个 `Id` 属性,该属性在 JSON 中序列化为 `id`。

  1. Ctrl+Shift+A 打开添加新项对话框。向项目中添加一个新类 Family.cs

  2. 将 `Family`、`Parent`、`Child`、`Pet` 和 `Address` 类复制并粘贴到 Family.cs 中。请注意,您的命名空间将根据您的项目名称而有所不同。

    using Newtonsoft.Json;
    
    namespace CosmosGettingStartedDotnetCoreTutorial
    {
        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`,并将 `AddItemsToContainer` 方法添加到您的 `CreateContainer` 方法下方。该代码在创建项之前会检查是否存在具有相同 ID 的项。我们将插入两个项,分别用于 Andersen Family 和 Wakefield Family。

     /*
         Add Family items to the container
     */
     private async Task AddItemsToContainer()
     {
         // 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 = true
         };
    
         // 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.
         CosmosItemResponse<Family> andersenFamilyResponse = await this.container.Items.ReadItemAsync<Family>(andersenFamily.LastName, andersenFamily.Id);
    
         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.Items.CreateItemAsync<Family>(andersenFamily.LastName, andersenFamily);
    
             // Note that after creating the item, we can access the body of the item with the Resource property off the CosmosItemResponse.
             //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);
         }
    
         // 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 = false
         };
    
         // Read the item to see if it exists
         CosmosItemResponse<Family> wakefieldFamilyResponse = await this.container.Items.ReadItemAsync<Family>(wakefieldFamily.LastName, wakefieldFamily.Id);
    
         if (wakefieldFamilyResponse.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"
             wakefieldFamilyResponse = await this.container.Items.CreateItemAsync<Family>(wakefieldFamily.LastName, wakefieldFamily);
    
             // Note that after creating the item, we can access the body of the item with the Resource property off the CosmosItemResponse.
             //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);
         }
         else
         {
             Console.WriteLine("Item in database with id: {0} already exists\n", wakefieldFamilyResponse.Resource.Id);
         }
     }
    
  4. 在 `GetStartedDemoAsync` 方法中添加对 `AddItemsToContainer` 的调用。

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

F5 运行您的应用程序。

恭喜!您已成功创建了两个 Azure Cosmos DB 项。

步骤 7:查询 Azure Cosmos DB 资源

Azure Cosmos DB 支持对存储在每个 collection 中的 JSON 文档进行丰富的查询。以下示例代码显示了如何查询我们在上一步中插入的项。

  1. 将 `RunQuery` 方法复制并粘贴到您的 `AddItemsToContainer` 方法下方。

    /*
        Run a query (using Azure Cosmos DB SQL syntax) against the container
    */
    private async Task RunQuery()
    {
        var sqlQueryText = "SELECT * FROM c WHERE c.LastName = 'Andersen'";
        var partitionKeyValue = "Andersen";
    
        Console.WriteLine("Running query: {0}\n", sqlQueryText);
    
        CosmosSqlQueryDefinition queryDefinition = new CosmosSqlQueryDefinition(sqlQueryText);
        CosmosResultSetIterator<Family> queryResultSetIterator = this.container.Items.CreateItemQuery<Family>(queryDefinition, partitionKeyValue);
    
        List<Family> families = new List<Family>();
    
        while (queryResultSetIterator.HasMoreResults)
        {
            CosmosQueryResponse<Family> currentResultSet = await queryResultSetIterator.FetchNextSetAsync();
            foreach (Family family in currentResultSet)
            {
                families.Add(family);
                Console.WriteLine("\tRead {0}\n", family);
            }
        }
    }
    
  2. 在 `GetStartedDemoAsync` 方法中添加对 `RunQuery` 的调用。

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

F5 运行您的应用程序。

恭喜!您已成功查询了 Azure Cosmos DB 容器。

步骤 8:替换 JSON 项

现在,我们将更新 Azure Cosmos DB 中的一个项。

  1. 将 `ReplaceFamilyItem` 方法复制并粘贴到您的 `RunQuery` 方法下方。请注意,我们将更改 Family 的 `IsRegistered` 属性和一个孩子的 `Grade`。

    /*
    Update an item in the container
    */
    private async Task ReplaceFamilyItem()
    {
        CosmosItemResponse<Family> wakefieldFamilyResponse = await this.container.Items.ReadItemAsync<Family>("Wakefield", "Wakefield.7");
        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.Items.ReplaceItemAsync<Family>(itemBody.LastName, itemBody.Id, itemBody);
        Console.WriteLine("Updated Family [{0},{1}]\n. Body is now: {2}\n", itemBody.LastName, itemBody.Id, wakefieldFamilyResponse.Resource);
    }
    
  2. 在 `GetStartedDemo` 方法中添加对 `ReplaceFamilyItem` 的调用。

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

F5 运行您的应用程序。

恭喜!您已成功替换了一个 Azure Cosmos DB 项。

步骤 9:删除项

现在,我们将删除 Azure Cosmos DB 中的一个项。

  1. 将 `DeleteFamilyItem` 方法复制并粘贴到您的 `ReplaceFamilyItem` 方法下方。

    /*
    Delete an item in the container
    */
    private async Task DeleteFamilyItem()
    {
        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
        CosmosItemResponse<Family> wakefieldFamilyResponse = await this.container.Items.DeleteItemAsync<Family>(partitionKeyValue, familyId);
        Console.WriteLine("Deleted Family [{0},{1}]\n", partitionKeyValue, familyId);
    }
    
  2. 在 `GetStartedDemo` 方法中添加对 `DeleteFamilyItem` 的调用。

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

F5 运行您的应用程序。

恭喜!您已成功删除了一个 Azure Cosmos DB 项。

步骤 10:删除数据库

现在我们将删除我们的数据库。删除创建的数据库将删除数据库及其所有子资源(容器、项以及任何存储过程、用户定义函数和触发器)。我们还将处理 `CosmosClient` 实例。

  1. 将 `DeleteDatabaseAndCleanup` 方法复制并粘贴到您的 `DeleteFamilyItem` 方法下方。

    /*
    Delete the database and dispose of the Cosmos Client instance
    */
    private async Task DeleteDatabaseAndCleanup()
    {
        CosmosDatabaseResponse 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. 在 `GetStartedDemo` 方法中添加对 `DeleteDatabaseAndCleanup` 的调用。

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

F5 运行您的应用程序。

恭喜!您已成功删除了一个 Azure Cosmos DB 数据库。

步骤 11:一起运行您的 C# 控制台应用程序!

在 Visual Studio 中按 F5 以在调试模式下构建应用程序。

您应该会在控制台窗口中看到整个入门应用程序的输出。输出将显示我们添加的查询结果,并且应与下面的示例文本匹配。

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.

恭喜!您已完成教程,并拥有了一个可正常工作的 C# 控制台应用程序!

获取完整的教程解决方案

要构建包含本文档中所有示例的 GetStarted 解决方案,您需要以下各项

要在 Visual Studio 中还原 Azure Cosmos DB .NET Core SDK 的 SQL API 引用,请在解决方案资源管理器中右键单击 GetStarted 解决方案,然后选择 还原 NuGet 程序包。接下来,在 Program.cs 文件中,按照 连接到 Azure Cosmos DB 帐户 中的说明更新 EndpointUriPrimaryKey 值。

后续步骤

在本教程中,您已了解如何构建一个 .NET Core 应用程序来管理 Azure Cosmos DB SQL API 数据。现在您可以将其他数据导入您的 Azure Cosmos DB 帐户。

© . All rights reserved.