Search code examples
azure-cosmosdb

Adding a property to existing data in ComsosDB


In my ASPCoreNet using entity framework, I have a database of Record:

public class Record
{
  public int Val1 {get;set;} = 0;
}

And the DB is full of this.

If I then want to add a new value:

public class Record
{
  public int Val1 {get;set;} = 0;
  public int Val2 {get;set;} = 0;
}

This now causes every query to fail with 'Nullable object must have a value.'. The desired behavior is 'if a property doesnt exist, just ignore it and dont crash'. Is this possible with CosmosDB? (I'd prefer not to make it nullable)


Solution

  • In Cosmos DB, if you add a new property to your Record class, existing documents without that property will cause issues if the property isn't nullable. To avoid the "Nullable object must have a value" error, you can handle this by initializing the property with a default value or using a custom serializer to ignore missing properties during deserialization. However, the simplest approach is to make the new property nullable:

    public class Record
    {
      public int Val1 { get; set; } = 0;
      public int? Val2 { get; set; } // Nullable property
    }
    

    This ensures that queries won't fail when the property is missing in existing documents. If you prefer not to use nullable types, you'll need to implement a custom deserialization logic to handle missing properties gracefully.