Optional One-to-many Relationship in Entity Framework

10,227

You can try this:

this.HasOptional(s => s.Department)
    .WithMany(s => s.Members)
    .HasForeignKey(s => s.MemberOfDepartment);
Share:
10,227
givemelight
Author by

givemelight

Updated on July 16, 2022

Comments

  • givemelight
    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 a Person. When assigned, the Person should show up in the Members-List of the Department.

    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 the Person:

    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?