Optional One-to-many Relationship in Entity Framework
You can try this:
this.HasOptional(s => s.Department)
.WithMany(s => s.Members)
.HasForeignKey(s => s.MemberOfDepartment);
givemelight
Updated on July 16, 2022Comments
-
givemelight almost 2 years
I'm having issues getting an optional one-to-many relationship to work.
My model is:
public class Person { public int Identifier { get; set; } ... public virtual Department Department { get; set; } } public class Department { public int Identifier { get; set; } ... public virtual IList<Person> Members { get; set; } }
I want to assign zero or one
Department
to aPerson
. When assigned, thePerson
should show up in theMembers
-List of theDepartment
.I'm configuring the
Person
using the Fluent API like this:HasKey(p => p.Identifier); HasOptional(p => p.Department).WithMany(d => d.Members);
Also tried the other way by configuring the
Department
instead of thePerson
:HasMany(d => d.Members).WithOptional(p => p.Department);
However with both ways I'm getting the Exception:
Unable to determine the principal end of an association between the types 'Person' and 'Department'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
When configuring both like that at the same time, I'm getting:
The navigation property 'Department' declared on type 'Person' has been configured with conflicting multiplicities.
Using the same configuration as the one for
Person
for another entity type works, however that entity type references itself.How to properly configure this relationship?