Cosmos DB .NET SDK v3 versus v4: where is my id

A major version means breaking changes. This time it meant runtime errors even though code compiled.

While most of you might experience this (or a similar) issue when doing an upgrade to the Cosmos DB .NET SDK v4, I experienced problems when doing a downgrade from the v4 prerelease SDK to v3 as I needed some features currently not available in v4 yet.

The v4 release is a complete overhaul of the SDK to align with other Azure SDKs, including namespace changes (dropping Microsoft.) and type renames (e.g. CosmosContainer instead of Container). So switching between v3 and v4 (upgrade or downgrade) means you’ll have some work to make everything compile again. Once that was done, I expected everything to ‘just work’. However, starting my Azure WebJob (consuming Azure Service Bus messages) locally, I received an exception on the very first UpsertItemAsync method call.

{"Errors":["One of the specified inputs is invalid"]}

There aren’t many properties in your object that can be invalid as we’re using a NoSQL store which is known for free-form schemas. One of them is id, then there’s also a handful of system generated properties which al start with an underscore. Finally there’s your own defined partition key, but this can be null (or missing) in which case the document is stored in the ‘null’ partition. I decided to test again with the CreateItemAsync method and received following error.

{"Errors":["The input content is invalid because the required properties - id; - are missing"]}

My first reaction was: how is this possible, I’ve placed attributes on my models and this code ran before.

    [JsonPropertyName("id")]
    public string DataHubId { get; set; }

I went for the ‘Clean solution’ command, did a full rebuild and tried again … without luck. After some searching I found this issue which explained the hard dependency on Newtonsoft.Json in the v3 SDK. Those who work with JSON documents from .NET code on a regular base might have noticed that the above attribute lives in the System.Text.Json.Serialization namespace, while the code below has an attribute from the Newtonsoft.Json namespace. Switching all attributes fixed my problem, meaning we’ll probably switch them all back in a few months when moving to the SDK v4 as System.Text.Json.Serialization has a better performance and doesn’t require a third party NuGet package.

    [JsonProperty("id")]
    public string DataHubId { get; set; }

Example code for both SDK versions is available on Github.

Licensed under CC BY-NC-SA 4.0; code samples licensed under MIT.
comments powered by Disqus
Built with Hugo - Based on Theme Stack designed by Jimmy