Allow value types as optional properties, using the sentinel value to detect when they're set #34943
Description
We currently disallow value type properties to be marked as optional:
Unhandled exception. System.InvalidOperationException: The property 'Blog.Foo' cannot be marked as nullable/optional because the type of the property is 'int' which is not a nullable type. Any property can be marked as non-nullable/required, but only properties of nullable types can be marked as nullable/optional.
at Microsoft.EntityFrameworkCore.Metadata.Internal.Property.SetIsNullable(Nullable`1 nullable, ConfigurationSource configurationSource)
at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalPropertyBuilder.IsRequired(Nullable`1 required, ConfigurationSource configurationSource)
at Microsoft.EntityFrameworkCore.Metadata.Builders.PropertyBuilder.IsRequired(Boolean required)
at Microsoft.EntityFrameworkCore.Metadata.Builders.PropertyBuilder`1.IsRequired(Boolean required)
at BlogContext.OnModelCreating(ModelBuilder modelBuilder) in /Users/roji/projects/test/Program.cs:line 28
On the other hand, for the purpose of value generation, we have the concept of a sentinel (CLR default by default) which informs us whether a property is set or not (if unset and value generation is configured, we don't send the value to the database). We've also been discussing how to handle missing properties in documents (JSON), and the ability to read such documents back (especially for scenarios where a JSON "schema" evolves to include a new property, at which point all existing documents are missing it). It seems we could use the same principles and materialize a database null to the property default/sentinel, allowing optional value type properties.
/cc @AndriySvyryd
Raised by @burikella in #34940 for the Option<T>
type.
Activity