c# - 具有 id 的实体已存在且在 CosmosDB 中不同时存在

标签 c# azure-functions azure-cosmosdb

我正在用头撞墙。
我有一个基本上是 Upsert 的函数,名为 TryCreateOrUpdate .我确实意识到现在存在一个 upsert 函数,但这是一些较旧的代码。这是函数:

public static async Task<string> TryCreateOrUpdate<T>(T data) where T : ViewModelBase
{
    var options = string.IsNullOrWhiteSpace(data.PartitionKey) ? null : new RequestOptions { PartitionKey = new PartitionKey(data.PartitionKey) };
    try
    {
        var response = await Client.CreateDocumentAsync(Collection.SelfLink, data, options, true);
    }
    catch (DocumentClientException dce)
    {
        switch (dce.StatusCode.Value)
        {
            ...
            case HttpStatusCode.Conflict:
                try
                {
                    var link = UriFactory.CreateDocumentUri(_databaseId, _collectionId, data.Id);
                    await Client.ReplaceDocumentAsync(link, item, options);
                }
                catch (Exception e)
                {
                    return $"There was an error updating the document.";
                }
                break;
            default:
                ...
        }
    }
    catch (Exception e)
    {
        return "There was an unknown error creating the document.";
    }
    return "OK";
}

我正在尝试插入一个 id 为 6 位数的文档作为字符串。
我检查了我的 Cosmos DB,我可以确认数据库中没有我试图更新的 ID 的文档。所以它应该导致创建。
创建文档的行抛出 DocumentClientException :

Entity with the specified id already exists in the system.


但是,替换代码行会引发此异常:

Entity with the specified id does not exist in the system.


嗯什么?到底存在不存在?!
正如我所说,我在运行之前进行了检查,并且该文档不存在。
我什至尝试更改所有这些代码以使用较新的 UpsertDocumentAsync我仍然收到错误

Entity with id already exists in the system


尽管如此,正如我所说,该文件不存在。

最佳答案

虽然我不太了解与此问题相关的 CosmosDb 和相关包的内部工作原理,但似乎原因是重写了基类中的 Id 字段的编写方式。

以前是这样写的:

public string id => Id;

public string Id { get; set; }

然后它变成了:
[JsonProperty("id")]
public string Id { get; set; }

请注意, id => Id 已被删除。现在它引起了问题。我们将其更改为:
public string id {
    get { return Id; }
    set { Id = value; }
}

public string Id { get; set; }

现在一切都像以前一样。

关于c# - 具有 id 的实体已存在且在 CosmosDB 中不同时存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57385244/

相关文章:

C# WPF 将英文数字转换为阿拉伯数字

类似 Azure Functions 的解决方案,能够运行 Win32 桌面应用程序

c# - 如何使用 LIKE 关键字简化或重写 Cosmos 查询

无需注册 Azure 即可实现 Java DocumentDB 连接

c# - CosmosDb - 写入操作导致错误。错误=16500

sql - 将 VALUE 关键字与文档数据库中的其他 SELECT 元素组合

c# - 存在同名数据库,或无法打开指定文件,或位于 UNC 共享上。这是什么意思?

c# - 交换单元格数据会违反唯一约束,尽管整体更改是有效的

c# - 这段代码在 C# 中做了什么,它的目的是什么?

azure - 如何让某些代码仅在Azure函数第一次运行时运行?