Optional One-to-many Relationship in Entity Framework

巧了我就是萌 提交于 2019-12-01 20:18:04

问题


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:


You can try this:

this.HasOptional(s => s.Department)
    .WithMany(s => s.Members)
    .HasForeignKey(s => s.MemberOfDepartment);



回答2:


modelBuilder.Entity().HasMany(x => x.MemberOfDepartment).WithOptional();



来源:https://stackoverflow.com/questions/29306040/optional-one-to-many-relationship-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!