I have a somewhat special scenario of a Zero-or-one relationship in EF Core which cannot be easily modeled by the default (as described, e.g.,in EF Core One to One or Zero Relationship).
I've got multiple entities with a 0-1 relationship to a "Match" entity. Multiple instances can reference the same "Match" entity (which is why I can't put the foreign key into the "Match" table, which seems to be the recommended way of modeling a 0-1 relationship).
How to define the relationship from one of the entities to 0-1 "Match" entities? Do I have to create a Match().HasMany(someKindOfBaseClassOfEntities) instead? Is there a better way?
You can configure this by using
HasOne, which allows a 1:0..1 relationship. Just showing one way of doing this without repeating too much mapping code:Classes:
Mapping configuration:
The type of
HasMatchBase.MatchIDdetermines whether the association is required or optional. In this case it's a nullableint, turning the association intoMatchbeing optional.