Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

c# - CosmosDB SQL Api not persisting Enum values 0


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
    public string CreatorId { get; private set; }

    public SessionStatus SessionStatus { get; private set; }
public enum SessionStatus


var document = await cosmosDbClient.CreateDocumentAsync(session);


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.

Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share