azure - 需要帮助将项目插入 Cosmos Collection

标签 azure .net-core azure-cosmosdb

我必须将一个项目插入集合中。我必须 GetProvider 的代码可以工作,但使用 Microsoft.Azure.Documents.Client 类。我在微软的网站上找到了一些示例代码来进行插入。它需要使用 Microsoft.Azure.Cosmos 类。代码有一个错误,容器未定义。因此,我添加了 Container 容器,这清除了该错误,但由于没有初始化程序,我现在遇到了使用未初始化对象错误。我的应用程序是 .NET Core 3.0 WEB API。

下面的代码是我实现插入的方式。有没有办法只使用 Microsoft.Azure.Cosmos 库进行插入?

using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SchedulingAppointmentAPI.Models;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using Microsoft.Azure.Cosmos;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents;
using ConnectionMode = Microsoft.Azure.Documents.Client.ConnectionMode;
using Database = Microsoft.Azure.Documents.Database;
using PartitionKey = Microsoft.Azure.Cosmos.PartitionKey;

public async void SaveAppointment(Appointments appointment)
        {
            try
            {
                using (client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey,
                      new ConnectionPolicy { ConnectionMode = ConnectionMode.Gateway, ConnectionProtocol = Protocol.Https }))
                {
                    Database databasename = await client.CreateDatabaseIfNotExistsAsync(new Database { Id = DatabaseName });
                    DocumentCollection collectionname = await GetOrCreateCollectionAsync(DatabaseName, CollectionName);
                    Container container;// = await Database.CreateContainerAsync("container-id");
                    Uri collectionUri = UriFactory.CreateDocumentCollectionUri(DatabaseName, CollectionName);

                    try
                    {
                        // Read the item to see if it exists.  
                        ItemResponse<Appointments> appointmentItemResponse = await container.ReadItemAsync<Appointments>(appointment.id.ToString(), new PartitionKey(appointment.Provider_Id));
                    }

                    catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
                    {
                        // Create an item in the container representing the appointment. Note we provide the value of the partition key for this item, which is "ProviderID"
                        ItemResponse<Appointments> appointmentItemResponse = await container.CreateItemAsync<Appointments>(appointment, new PartitionKey(appointment.Provider_Id));

                    }

最佳答案

正如@David正确指出的那样,由于容器未初始化,您会收到空引用错误,您可以使用如下所示的内容:

我们的 Cosmos DB 中需要一个数据库和几个集合。

var client = new CosmosClient(Endpoint, Authkey);
await client.Databases.CreateDatabaseIfNotExistsAsync("DatabaseId", 400);
await client.Databases["DatabaseId"].Containers.CreateContainerIfNotExistsAsync("ContainerA", "/partitionKey");
await client.Databases["DatabaseId"].Containers.CreateContainerIfNotExistsAsync("ContainerB", "/partitionKey");

要获取现有数据库/集合的元数据,我们可以这样做:

await client.Databases["DatabaseId"].ReadAsync();
await client.Databases["DatabaseId"].Containers["ContainerA"].ReadAsync();

为了创建实体,我们需要:

var item = new SampleEntity
{
    Id= Guid.NewGuid().ToString(),
    Name = "Sample",
    PartitionKey = "a"
};
CosmosItemResponse<SampleEntity> res = await container.Items.CreateItemAsync(item.PartitionKey, item);

您可以引用以下存储库来管理容器:

https://github.com/Azure/azure-cosmos-dotnet-v3/blob/master/Microsoft.Azure.Cosmos.Samples/Usage/ContainerManagement/Program.cs

其他引用:

https://joonasw.net/view/exploring-cosmos-db-sdk-v3

希望有帮助。

关于azure - 需要帮助将项目插入 Cosmos Collection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59461212/

相关文章:

c# - 如何在.NET Core中获取IServiceProvider的实例?

c# - AWS 中跨 lambda 的连接池

azure - 如何在 Cosmos DB 中查找重复文档

php - 使用 Azure CosmosDB 的 REST API 获取文档

azure - 寻找替代解决方案来处理从 Azure Blob 到 Azure SQL DB 的数万个 JSON

azure - Power BI 与 Azure 分析服务

git - 如何使用Azure Pipeline创建新标签?

c# - Azure.Data.Tables.TableClient 是线程安全的吗?

c# - 是否可以在 CosmosDB 的 Azure Function 中完美监控 Change Feed 的工作

azure - 如何使用 Web 角色的多个实例保持 httprequest 顺序