C# CosmosDB SQL Api未持久化枚举值0
问题: 我正在开发一个.NET Core 5.0 web应用程序,它使用Cosmos DB作为我的持久性存储,当枚举设置为0(默认值)时,它似乎不会持久化枚举。在下面的代码中,当我创建会话时,默认的SessionStatus值是计划的。如果我将会话设置为“正在进行”或“已完成”。它在数据库中分别以1或2的值显示 我的代码 课时班C# CosmosDB SQL Api未持久化枚举值0,c#,.net-core,azure-cosmosdb,azure-cosmosdb-sqlapi,asp.net-core-5.0,C#,.net Core,Azure Cosmosdb,Azure Cosmosdb Sqlapi,Asp.net Core 5.0,问题: 我正在开发一个.NET Core 5.0 web应用程序,它使用Cosmos DB作为我的持久性存储,当枚举设置为0(默认值)时,它似乎不会持久化枚举。在下面的代码中,当我创建会话时,默认的SessionStatus值是计划的。如果我将会话设置为“正在进行”或“已完成”。它在数据库中分别以1或2的值显示 我的代码 课时班 public class Session { [JsonProperty("creator_id")] public string
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
}
回购:
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);
}
公共异步任务CreateDocumentAsync(对象文档,RequestOptions=null,
bool disableAutomaticIdGeneration=false,CancellationToken CancellationToken=default(CancellationToken))
{
返回等待_documentClient.createdocumentsync(
CreateDocumentCollectionUri(_databaseName,_collectionName),文档,选项,
disableAutomaticIdGeneration、cancellationToken);
}
我尝试过的:
所使用的底层JSON序列化程序似乎设置为忽略默认值。在创建cosmos数据库的客户机时,可以在选项中指定行为,但也可以使用JSON注释将范围限定为单个参数 默认情况下,Cosmos v2和v3使用序列化程序包
Newtonsoft.Json
,其中可以对单个参数使用[JsonProperty(DefaultValueHandling=DefaultValueHandling.Include)]
COSMOSV4默认使用System.Text.Json
,您可以使用[JsonIgnore(Condition=JsonIgnoreCondition.Never)]
执行相同的操作
不包括它的原因是,将默认值读写到CosmosDB会消耗一点额外的
RU
,并且可能不需要,因为在使用类模型时,它会反序列化为默认值。听起来您使用的JSON序列化程序设置为忽略默认值。您可以检查那里的选项,或者如果您只想为此属性单独设置,请添加属性[JsonProperty(DefaultValueHandling=DefaultValueHandling.Include)]
。这就成功了!!不知道为什么它不会被设置为包括在第一位。。。。
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);
}