-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Description
Suppose I have an entity like this:
public class Todo
{
public string Id { get; set; }
public string Title { get; set; }
public bool IsDone { get; set; }
}
If the container has a document with no value defined for IsDone
, trying to load it throws an InvalidOperationException
: Nullable object must have a value
.
Although I understand the reason for this, it means my code can never handle documents where IsDone
is null or undefined (which can happen, for instance, if the property didn't exist in the beginning but was added later). I could make the property nullable in the entity, but then I would need to handle the null case everywhere the property is used, which isn't ideal.
Also, if I query with a filter like .Where(t => !t.IsDone)
, documents where the IsDone
property is undefined are not returned. I understand that it's because of the Cosmos DB semantics (null or undefined is neither true nor false), but it would be nice if null or undefined could be handled as if it was a default value (false in this case). See also Azure/azure-cosmos-dotnet-v3#682.
I think this could easily be handled by supporting a default value. This value could either be specified with a [DefaultValue]
attribute on the property, or with a HasDefaultValue(T value)
method in the fluent model builder API. The effect would be to change the SQL from NOT(doc['IsDone'])
to NOT(doc['IsDone'] ?? <defaultValue>)
.
I think it would be a very valuable feature to make data model evolutions easier. Currently, if I want to add a property when the container already contains documents, I have to either make it nullable (which isn't ideal if it's not supposed to be null) or update all documents to add the property.