Azure C# Cosmos DB: 属性 "id" 在实际存在时丢失

Azure C# Cosmos DB: Property "id" is missing when it's actually present

我现在开始使用 CosmosDB,我 运行 在尝试向数据库中插入一些数据时遇到以下错误:

The input content is invalid because the required properties - 'id; ' - are missing.

我知道我的文档中应该有一个名为 idstring 字段,但是即使我将 [JsonPropertyName("id")] 作为注释添加到我的对象的 [=18] 中,错误仍然存​​在=] 字段.

这是对 CosmosDB 的调用:

var insertionResponse = await container.CreateItemAsync<Article>(
    item: article,
    partitionKey: new PartitionKey(article.Id.ToString())
);

这里是 Article class:

public partial class Article
{
    [JsonPropertyName("id")]
    public Guid Id { get; set; }
    public Guid CreatedBy { get; set; }
    public DateTime CreatedOn { get; set; }

    public string Title { get; set; }
    public string Body { get; set; }
}

知道为什么会这样吗?

问题的发生是因为您的代码和 SDK 使用了不同的 JSON 库。您的代码使用 System.Text.Json,而 SDK 默认使用 Newtonsoft.Json serialization/deserialization。因此,SDK 不理解 [JsonPropertyName("id")] 属性,因此无法正确序列化文档。

2 可能的解决方案:

  1. 使用Newtonsoft.Json代替System.Text.Json

  2. 配置 SDK 以将 System.Text.Json 用于 serialization/deserialization。请参阅此 link 了解更多详情:https://github.com/ealsur/ondotnet-cosmosdb/tree/master/src/episode1/customserializer.

更新

我 运行 不久前遇到了完全相同的问题,我联系了一位 Cosmos DB SDK 团队成员。他向我指出了我在上面 #2 中分享的 link。他提到的警告是,如果您使用的是 LINQ 查询,则使用 System.Text.Json 可能不起作用。

其他替代方法(尽管不推荐)是使用默认使用 System.Text.Json 的 Cosmos DB SDK 版本 4。它目前处于预览阶段,根据 SDK 团队的评论,发布日期没有预计到达时间。此外,并非所有在 SDK 版本 3 中可用的功能现在在版本 4 中都可用(因此上面的“不推荐”评论)。

更新 2

使用 System.Text.Json 和 Cosmos DB SDK v3 有一个更好的实现(比我之前在 #2 中分享的实现)。请参阅此 link 了解更多详情:https://github.com/Azure/azure-cosmos-dotnet-v3/tree/master/Microsoft.Azure.Cosmos.Samples/Usage/SystemTextJson.