Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - CosmosDB SQL Api not persisting Enum values 0

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...