这个问题已经被问了很多次,甚至有几次答对了,我都看过了,然而,无论我做什么,它都会发生在我身上.以下是代码:

正在创建容器:

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

推荐答案

string partitionKeyPath = $"/{_userId}";

容器的分区键定义应该是name of the property and its path,而不是值.

例如,假设您的文档具有_userId属性,则它应该是:

string partitionKeyPath = "/_userId";

当您执行项操作时,您可以正确地传递Partition Key Value,即该文档的_userId属性值.

如果属性名称不是_userId,只需将代码更改为正确的属性名称即可.

Csharp相关问答推荐

我应该将新的httpReportMessage()包装在using声明中吗?

NumPy s fftn in C#with pythonnet'

将轮询与超时同步

C#-VS2022:全局使用和保存时的代码清理

如何使用XmlSerializer序列化带有CDATA节的XML文件?

取决于您的数据量的多个嵌套循环

在C#中,非静态接口方法的抽象和虚拟是冗余的吗?

有没有类似于扩展元素的合并元组的语法?

按需无缝转码单个HLS数据段

MSTest--将消息直接写入StdOut和使用TestContext有什么不同?

升级后发出SWITCH语句

在PostgreSQL上使用ExecuteSqlRawAsync的C#11原始字符串文字有区分大小写的问题

如何强制新设置在Unity中工作?

EF Core 7-忽略模型绑定中的虚拟属性

如何在一次数据库调用中为ASP.NET核心身份用户加载角色

如何解决System.StackOverflowException:抛出System.StackOverflowException类型的异常.&# 39;生成随机代码时发生异常?

如何在C# WinForm控件中使用Windows 10/11的黑暗主题?

使用postman 测试配置了身份的.NET 6应用程序

如何查找Span;T&>是否包含相同顺序的其他Span<;T&>

MS Project读取项目自定义域