Anduril
Anduril

Reputation: 1276

OwnsOne with nullable principal key errors

I am trying to configure an entity that can optionally belong to a group, but am getting an error that I think is caused by the key being nullable. I am using EF core 5

The main parent entity is configured as

public class Option 
{
    public int Id { get; set; }
    public int? GroupId { get; set; }

    public virtual Group Group { get; set; }
}

and a group is configured as

public class Group
{
    public int Id { get; set; }
}

The mapping is configured as

builder.Entity<Option>().OwnsOne(o => o.Group, b =>
{
    b.WithOwner().HasPrincipalKey(o => o.GroupId).HasForeignKey(x => x.Id);
});

However, this results in the error System.Data.SqlTypes.SqlNullValueException: Data is Null. This method or property cannot be called on Null values. It seems to be an issue with a nullable principal key. Am I configuring this relationship wrong, or is optional owned entities just not a scenario EF supports?

Upvotes: 1

Views: 1170

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205789

Am I configuring this relationship wrong, or is optional owned entities just not a scenario EF supports?

The later. The owner cannot be optional. It is required. That's essentially what distinguishes owned entity types from the regular (non owned) ones as mentioned in the documentation:

Owned entities are essentially a part of the owner and cannot exist without it

If you want optional principal, then configure the dependent as regular entity having 0 or 1 (optional one-to-one) relationship with the principal. This also would require them to have their own table, since they cannot share the same table (a.k.a. table splitting) because it also requires the primary (principal) entity to exists, and only dependent(s) could be optional.

Upvotes: 2

Related Questions