我必须将一个项目插入集合中。我必须对GetProvider使用的代码可以使用Microsoft.Azure.Documents.Client类。我在Microsoft网站上找到了一些示例代码来进行插入。它需要使用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));
}
答案 0 :(得分:0)
正如@David所正确指出的那样,由于容器未初始化,您将得到null引用错误,您可以使用类似以下的内容:
我们在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://joonasw.net/view/exploring-cosmos-db-sdk-v3
希望有帮助。