I'm getting started with CosmosDB now and I'm running into the following error when trying to insert some data in the database:
The input content is invalid because the required properties - 'id; ' - are missing.
I understand that there should be a string
field called id
in my document, but the error persists even after I add [JsonPropertyName("id")]
as an annotation to my object's Id
field.
Here's the call to CosmosDB:
var insertionResponse = await container.CreateItemAsync<Article>(
item: article,
partitionKey: new PartitionKey(article.Id.ToString())
);
And here's the 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; }
}
Any ideas why this is happening?
The issue is happening because of different JSON libraries being used by your code and the SDK. Your code is using System.Text.Json
whereas the SDK uses Newtonsoft.Json
by default for serialization/deserialization. Because of this, the SDK does not understand [JsonPropertyName("id")]
attribute and does not serialize the document properly.
2 Possible solutions:
Use Newtonsoft.Json
instead of System.Text.Json
.
Configure the SDK to use System.Text.Json
for serialization/deserialization. Please see this link for more details: https://github.com/ealsur/ondotnet-cosmosdb/tree/master/src/episode1/customserializer.
UPDATE
I ran into the exact same issue not too long ago and I reached out to one of the Cosmos DB SDK team member. He pointed me to the link I shared in #2 above. Caveat he mentioned is that using System.Text.Json
might not work if you're using LINQ queries.
Other alternative (though not recommended) is to use version 4 of the Cosmos DB SDK which uses System.Text.Json by default. It is currently in preview and as per the comments from the SDK team, there's no ETA on the release date. Furthermore, not all features that are available in SDK version 3 are available in version 4 as of now (hence "not recommended" comment above).
UPDATE 2
There's a better implementation (than what I shared earlier in #2) of using System.Text.Json with v3 of Cosmos DB SDK. Please see this link for more details: https://github.com/Azure/azure-cosmos-dotnet-v3/tree/master/Microsoft.Azure.Cosmos.Samples/Usage/SystemTextJson.