How to make an OwnsOne property in EF Core 3.0 required when mapping to SQL Server columns?
I reached out to the EF Core team and currently the only way to do this would be to manually change the migration that is created to set nullable = false. It has been flagged as a feature request so let's hope one day they get it fixed!
EF Core 5
In addition to set .IsRequired()
on the required properties within the ValueObject
,
you need to configure the navigation as required after x.OwnsOne(...)
:
builder.OwnsOne(o => o.Address, a =>
{
a.WithOwner();
a.Property(p => p.Street)
.IsRequired();
a.Property(p => p.ZipCode)
.IsRequired();
a.Property(p => p.City)
.IsRequired();
}).Navigation(p => p.Address).IsRequired();
=============^========================================^
Issue: https://github.com/dotnet/efcore/issues/12100
Credits to: @AndriySvyryd