这个问题已经被问了很多次,甚至有几次答对了,我都看过了,然而,无论我做什么,它都会发生在我身上.以下是代码:
正在创建容器:
string partitionKeyPath = $"/{_userId}";
_container = await database.CreateContainerIfNotExistsAsync(_containerName, partitionKeyPath);
然后,当添加我的聊天对象的时候:
if (_container != null)
{
Chat? chat;
bool newChatCreated = false;
try
{
// Attempt to read the Chat item. If it exists, add the ChatItem to it.
chat = await _container.ReadItemAsync<Chat>(chatId, new PartitionKey(_userId)).ConfigureAwait(false);
}
catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
// If the Chat item does not exist, create a new one.
chat = new Chat
{
id = chatId,
_userId = _userId,
ChatItems = new List<ChatItem>(),
ChatName = chatName,
IndexName = indexName,
TimeCreated = DateTime.Now.ToString("yyyy/MM/dd-HH:mm:ss.fff")
};
ContainerProperties props = await _container.ReadContainerAsync();
_logger.LogInformation($"PartitionKeyPath: {props.PartitionKeyPath}");
// Exception happens on the next line in CreateItemAsync !!!
await _container.CreateItemAsync<Chat>(chat, new PartitionKey(_userId));
newChatCreated = true;
}
chat?.ChatItems?.Add(chatItem);
if (newChatCreated)
{
// Update the Chat item in the database
await _container.ReplaceItemAsync<Chat>(chat, chatId, new PartitionKey(_userId));
}
else
{
var patchOperations = new List<PatchOperation>
{
PatchOperation.Add("/ChatItems/-", chatItem)
};
await _container.PatchItemAsync<Chat>(chatId, new PartitionKey(_userId), patchOperations);
}
}
else
{
_logger.LogError("_container is null");
return false;
}
用作PartitionKey的_UserID全部是字母数字小写:"supportgpt4office ecom". PartionKeyPath相同,但前缀为‘/’,即:"/supportgpt4office ecom"(通过在调用之前记录它来验证).
有谁能给我解释一下这是怎么回事吗? 顺便说一句,我正在运行最新的CosmosDB版本: Microsoft.Azure.CosmosDB 3.37.1