Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Problem:

I am working on a .NET Core 5.0 web app that is using Cosmos DB as my persistence store and it does not seem to be persisting enums when they are set to 0 (default value). In the code below, when I create a session, the default SessionStatus value is Planned. If I set the Session to InProgress or Completed. It shows up in the database with a value of 1 or 2 respectively.

My Code Session Class

public class Session
{
    [JsonProperty("creator_id")]
    public string CreatorId { get; private set; }

    [JsonProperty("session_status")]
    public SessionStatus SessionStatus { get; private set; }
}
public enum SessionStatus
{
    Planned,
    InProgress,
    Completed
}

Repo:

var document = await cosmosDbClient.CreateDocumentAsync(session);

CosmosClient:

public async Task<Document> CreateDocumentAsync(object document, RequestOptions options = null,
    bool disableAutomaticIdGeneration = false, CancellationToken cancellationToken = default(CancellationToken))
{
    return await _documentClient.CreateDocumentAsync(
        UriFactory.CreateDocumentCollectionUri(_databaseName, _collectionName), document, options,
        disableAutomaticIdGeneration, cancellationToken);
}

What I have tried:

  1. I have tried setting enum json converted on the Enum object to store as a string in db, but same behavior for session_status in db.
  2. I could set the default value for SessionStatus to 1 as a work around, but would rather understand the underyling issue.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.5k views
Welcome To Ask or Share your Answers For Others

1 Answer

It seems like the underlying JSON serializer that is used is set to ignore default values. The behaviour can be specified in the options when creating a client to the cosmos database, but can also be scoped to individual parameters using the JSON annotations.

Cosmos v2 & v3 by default use the serializer package Newtonsoft.Json, where you can use [JsonProperty(DefaultValueHandling = DefaultValueHandling.Include)] on an individual parameter to always write it.

Cosmos v4 uses System.Text.Json by default where you can do the same using [JsonIgnore(Condition = JsonIgnoreCondition.Never)].

The reason to not include it would be that reading & writing the default value to your CosmosDB consumes a little extra RU and might not be needed as it gets deserialized to its default value anyway when working with a class model.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...