Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an OwnsOne property in EF Core 3.0 required when mapping to SQL Server columns?

I have a main entity Profile that has a property Name that is a value object. The Name object has two properties First and Last. When I use the Fluent API to map the Name objects properties to columns within the Profile table I specify that they are required. When I create the migration it says nullable is true. I assume it has to do with the fact that in EF Core 3.0 owned entities are now optional but how do I tell EF that they are actually required?

public class Profile
{
   public Name Name { get; private set; }
   ...
}
public class Name
{
   public string First { get; }
   public string Last { get; }
   ...
}
public override void Configure(EntityTypeBuilder<Profile> builder)
{
   base.Configure(builder);

   builder.OwnsOne(
                navigationExpression: p => p.Name,
                buildAction: n =>
                {
                    n.Property(n => n.First)
                        .HasColumnName("NameFirst")
                        .HasMaxLength(25)
                        .IsRequired();

                    n.Property(n => n.Last)
                        .HasColumnName("NameLast")
                        .HasMaxLength(25)
                        .IsRequired();
                });
}

Any help you can provide would be great.

like image 345
Ken Brannigan Avatar asked Oct 16 '19 15:10

Ken Brannigan


2 Answers

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

like image 73
Maicon Heck Avatar answered Oct 31 '22 19:10

Maicon Heck


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!

like image 36
Ken Brannigan Avatar answered Oct 31 '22 19:10

Ken Brannigan