简体   繁体   中英

Optional One-to-many Relationship in Entity Framework

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?

You can try this:

this.HasOptional(s => s.Department)
    .WithMany(s => s.Members)
    .HasForeignKey(s => s.MemberOfDepartment);
modelBuilder.Entity<Department>().HasMany(x => x.MemberOfDepartment).WithOptional();

Also try this:

public class Person
{
    public int Identifier { get; set; }
    public int DepartmentIdentifier {get; set;}
    public virtual Department Department { get; set; }
}

public class Department
{
    public int Identifier { get; set; }

    public virtual IList<Person> Members { get; set; }
}

EF Person config using Fluent API:

this.HasRequired(p => p.Department).WithMany(d => d.Members).HasForeignKey(p => 
p.DepartmentIdentifier);

this.Property(p => p.DepartmentIdentifier).IsRequired();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM