I have the following two entities refering to one table using split table option from EF Core - this very simplified version:
class Account
int Id
Settings Settings
class Settings
int AccountId (maps to Id)
string PropertyX
From the documentation:
If all of the columns used by a dependent entity are NULL in the database, then no instance for it will be created when queried. This allows modeling an optional dependent entity, where the relationship property on the principal would be null. Note that this would also happen if all of the dependent's properties are optional and set to null, which might not be expected.
Is it possible to disable this behaviour? I have multiple columns with a lot of grouped behaviour that are default null.
Now the entity (Settings) won't be created by default. This means I have to nullcheck everywhere. I rather have Settings created with null values for all properties.
If I create the instance myself in the constructor of the parent entity (Account) the changes don't seem to be tracked, because I guess EF Core is not aware of the class.
Any solution?
Unfortunately this functionality is not available in EF Core 3.
The so called required dependent has been added in EF Core 5.0 - Required 1:1 dependents:
In EF Core 3.1, the dependent end of a one-to-one relationship was always considered optional. This was most apparent when using owned entities, as all the owned entity's column were created as nullable in the database, even if they were configured as required in the model.
In EF Core 5.0, a navigation to an owned entity can be configured as a required dependent
The above is just the announcement of the feature inside What's New section. In fact it can be used for any one-to-one relationship, as mentioned in the official One-to-one documentation section:
The dependent side is considered optional by default, but can be configured as required. However EF will not validate whether a dependent entity was provided, so this configuration will only make a difference when the database mapping allows it to be enforced. A common scenario for this are reference owned types that use table splitting by default
To configure the dependent as required, you have to use the Navigation
fluent API (also introduced in 5.0) combined with IsRequired
:
modelBuilder.Entity<Account>()
.Navigation(e => e.Settings)
.IsRequired();