📅  最后修改于: 2023-12-03 14:39:42.630000             🧑  作者: Mango
在本教程中,我们将介绍如何使用 C# 和 Azure Cosmos DB 将项目添加到容器中。Azure Cosmos DB 是一种分布式数据库服务,可在全球范围内提供所需的高可用性、全球分布和多模型支持。这意味着您可以在不同地域部署不同类型的应用程序,并无需自己管理和维护基础架构。
首先,我们需要创建一个 Azure Cosmos DB 帐户。请按照以下步骤操作:
现在,我们需要创建一个容器。请按照以下步骤操作:
接下来,我们需要编写 C# 代码,将项目添加到容器中。请按照以下步骤操作:
以下是代码示例:
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; }
}
}
}
请确保将以下变量替换为自己的值:
最后,我们需要运行代码并确保它可以将项目添加到容器中。请按照以下步骤操作:
在本教程中,我们介绍了如何使用 C# 和 Azure Cosmos DB 将项目添加到容器中。通过遵循这些步骤,您可以快速轻松地将项目添加到容器并将其部署到任意位置。