Optional One-to-many Relationship in Entity Framework

c# ef-fluent-api entity-framework entity-framework-6

Question

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?

1
5
4/1/2015 2:53:25 PM

Popular Answer

You can try this:

this.HasOptional(s => s.Department)
    .WithMany(s => s.Members)
    .HasForeignKey(s => s.MemberOfDepartment);
10
4/1/2015 4:08:30 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow