You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用C#更新Cosmos DB文档遇404错误求助

Cosmos DB 部分文档更新报404 NotFound 问题解决

问题核心错误点

你的代码存在三个关键问题,导致404错误:

  • 分区键参数传入错误:PartitionKey需要的是目标文档的分区键实际值,不是字段路径或名称。如果容器分区键是/id,你应该传入具体的文档id字符串,而不是"/id"这类值。
  • 泛型类型不匹配:PatchItemAsync<Person>中的Person类型和你的模型类Result不一致,SDK无法正确定位和处理文档。
  • Patch路径可能不匹配:模型属性是FirstName,如果Cosmos中存储的JSON字段是FirstName(取决于序列化配置),那么Patch路径应该是"/FirstName"而非"/firstName";如果序列化后是camelCase的firstName则没问题,但需要确认实际存储结构。

修复后的代码

public async Task UpdateFirstName(string id, string firstName)
{
    try
    {
        var response = await personContainer.PatchItemAsync<Result>(
            id: id,
            // 传入文档id作为分区键值(如果分区键确实是/id)
            partitionKey: new PartitionKey(id),
            patchOperations: new[] {
                // 注意路径要和实际存储的JSON字段名一致
                PatchOperation.Replace("/FirstName", firstName)
            }
        );

        var updated = response.Resource;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

额外验证步骤

  • 确认容器分区键设置:在Cosmos DB门户查看容器的分区键是否为/id。如果是其他字段,比如/FamilyName,则需要传入对应字段的实际值作为PartitionKey参数。
  • 检查文档实际结构:在数据资源管理器中查看目标文档的JSON,确认姓名字段的大小写,调整Patch路径。
  • 无分区键容器处理:如果容器是无分区键的旧版容器,将PartitionKey改为PartitionKey.None即可。

原问题信息

模型代码

public class Result
{
    public string id { get; set; }
    public string FirstName { get; set; } = "";
    public string FamilyName { get; set; } = "";
}

原更新方法代码

public async Task UpdateFirstName(string id, String firstName)
{
    try
    {
        var response = await personContainer.PatchItemAsync<Person>(
                 id: id,
                 partitionKey: new PartitionKey("/id"),
                 patchOperations: new[] {
                     PatchOperation.Replace("/firstName", firstName)
                 }
            );

        var updated = response.Resource;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

报错信息

Response status code does not indicate success: NotFound (404); Substatus: 0; ActivityId: 9da753ee-e64c-4ec2-a973-df7fae97b485;
Reason: (
Errors : [
"Resource Not Found. Learn more: https://aka.ms/cosmosdb-tsg-not-found"
]);

环境与尝试操作

  • 使用Microsoft.Azure.Cosmos 3.35.1版本
  • 其他查询(全量、按ID查询)功能正常
  • 尝试过的错误PartitionKey写法:
    partitionKey: new PartitionKey("/id"),
    partitionKey: new PartitionKey("@id"),
    partitionKey: new PartitionKey("id"),
    

内容的提问来源于stack exchange,提问作者Ashley Kilgour

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 07:23:07