1

I use CosmosDb with the Entity Framework. I need that when saving data if one of the properties is null, it is stored as undefined. Is there any option to initialize DbContext from CosmosClient, or set CosmosSerializationOptions?

I tried the following option, but it does not work for me:

context.Database.GetCosmosClient().ClientOptions.SerializerOptions = new CosmosSerializationOptions()
{
     IgnoreNullValues = true
};

The option without using EF is working:

CosmosClient cosmosClient = new CosmosClientBuilder(EndpointUri, PrimaryKey)
   .WithSerializerOptions(new CosmosSerializationOptions() { IgnoreNullValues = true })
   .Build();
//The current result
{
    "Id": "fad8b443-6d10-4009-853c-efb6aac18031",
    "Discriminator": "User",
    "FirstName": "Charley",
    "LastName": null
}
//Expected result
{
    "Id": "fad8b443-6d10-4009-853c-efb6aac18031",
    "Discriminator": "User",
    "FirstName": "Charley"
}
Roman Marusyk
  • 21,493
  • 24
  • 66
  • 105
Oleksandr
  • 69
  • 2
  • 7

1 Answers1

1

I've tried the sample and I found it really has no option to set IgnoreNullValues when initialize the client, and here's the description:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder.UseCosmos(
                "https://xxx.documents.azure.com:443/",
                "primary key",
                databaseName: "Tasks",
                options => {
                    options.SerializerOptions(....);//there's no property choice to set
                });

enter image description here

According to this situation, what you can do is modify the entity, such as removing the null property, and I found a similar question in st, I think you can refer to it. And if your entity always exists null value in some specific property(e.g one property 'userConf' may be a null property, you can create another entity without this property), you can even create another entity to meet your requirement.

Roman Marusyk
  • 21,493
  • 24
  • 66
  • 105
tiny-wa
  • 1,825
  • 1
  • 5
  • 13
  • I am all ears for a direct solution to set 'IgnoreNullValues = true ', I really can't find it. – tiny-wa Mar 02 '21 at 09:00
  • Yes, I tried to do this with CosmosDbContextOptionsBuilder in the UseCosmos method. The SerializerOptions property is available from under the DbContext object. – Oleksandr Mar 02 '21 at 09:14
  • @RomanMarusyk Yes, I see, I just wanna show there's no option for SerializerOptions, so I can't set this property when call 'UseCosmos', and I also tried to find the place to set it. If there's exactly nowhere to set, that means what I said is right. Thanks sir! – tiny-wa Mar 02 '21 at 09:27