📜  c# cosmos db 将项目添加到容器中 - C# (1)

📅  最后修改于: 2023-12-03 14:39:42.630000             🧑  作者: Mango

C# Cosmos DB 将项目添加到容器中

在本教程中,我们将介绍如何使用 C# 和 Azure Cosmos DB 将项目添加到容器中。Azure Cosmos DB 是一种分布式数据库服务,可在全球范围内提供所需的高可用性、全球分布和多模型支持。这意味着您可以在不同地域部署不同类型的应用程序,并无需自己管理和维护基础架构。

步骤
步骤 1:创建 Azure Cosmos DB 帐户

首先,我们需要创建一个 Azure Cosmos DB 帐户。请按照以下步骤操作:

  1. 打开 Azure 门户。
  2. 点击“创建资源”按钮,然后选择“数据库” > “Azure Cosmos DB”。
  3. 在“新建 Azure Cosmos DB 帐户”页面上,指定一个唯一的名称,选择一个 API,例如 SQL,然后选择您的订阅、资源组、位置。单击“查看 + 创建”。
  4. 在“新建 Azure Cosmos DB 帐户”页面上,选择“Azure Cosmos DB 利用服务终结点进行 VNet“。勾选后将使用 VNet 服务终结点来保护 Azure Cosmos DB 的所有数据流量。
  5. 点击“创建”按钮开始创建 Azure Cosmos DB 帐户。
步骤 2:创建一个容器

现在,我们需要创建一个容器。请按照以下步骤操作:

  1. 打开 Azure 门户。
  2. 浏览到您的 Azure Cosmos DB 帐户,然后单击“容器” > “新建容器”。
  3. 在“新建容器”页面上,指定容器的唯一名称,并选择一个分区键。
  4. 选择要为容器创建的类型, 例如“fixed”。
  5. 点击“创建”按钮开始创建容器。
步骤 3:编写 C# 代码

接下来,我们需要编写 C# 代码,将项目添加到容器中。请按照以下步骤操作:

  1. 在 Visual Studio 中创建一个新的 C# 控制台应用程序项目。
  2. 右键单击项目文件夹,然后单击“管理 NuGet 包”。
  3. 搜索“Microsoft.Azure.Cosmos”,然后安装该包。
  4. 打开 Program.cs 文件,并转到主方法。
  5. 声明一个名为“cosmosdb”的 CosmosClient 实例。
  6. 调用 CreateDatabaseIfNotExistsAsync() 方法创建数据库。
  7. 调用 CreateContainerIfNotExistsAsync() 方法并传递容器设置来创建容器。
  8. 向容器中添加项。

以下是代码示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos;

namespace CosmosDBDemo
{
    class Program
    {
        private static string endpointUrl = "https://<your-account-name>.documents.azure.com:443/";
        private static string primaryKey = "<your-primary-key>";
        private CosmosClient cosmosClient;
        private Database database;
        private Container container;

        static async Task Main(string[] args)
        {
            try
            {
                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();
            }
        }

        private async Task GetStartedDemoAsync()
        {
            // Create a new instance of the Cosmos Client
            this.cosmosClient = new CosmosClient(endpointUrl, primaryKey);

            // Create a new database
            this.database = await this.cosmosClient.CreateDatabaseIfNotExistsAsync("mydbc");

            // Create a new container
            this.container = await this.database.CreateContainerIfNotExistsAsync("mycontainer", "/partitionKey");

            // Add an item to the container
            MyItem item = new MyItem
            {
                Id = "123",
                PartitionKey = "123",
                Name = "John"
            };
            ItemResponse<MyItem> response = await container.CreateItemAsync(item);
            Console.WriteLine("Created item in database with id: {0}\n", response.Resource.Id);
        }

        public class MyItem
        {
            public string Id { get; set; }
            public string PartitionKey { get; set; }
            public string Name { get; set; }
        }
    }
}

请确保将以下变量替换为自己的值:

  • <your-account-name>
  • <your-primary-key>
  • "mydbc"
  • "mycontainer"
  • "/partitionKey"
步骤 4:运行代码

最后,我们需要运行代码并确保它可以将项目添加到容器中。请按照以下步骤操作:

  1. 保存并构建项目。
  2. 在 Visual Studio 中按 F5 键或 Ctrl + F5 键以运行代码。
  3. 查看输出窗口,确保可以看到成功的消息。
结论

在本教程中,我们介绍了如何使用 C# 和 Azure Cosmos DB 将项目添加到容器中。通过遵循这些步骤,您可以快速轻松地将项目添加到容器并将其部署到任意位置。