实体框架核心一对多

时间:2016-10-26 17:46:53

标签: asp.net-core-mvc entity-framework-core asp.net-core-1.0

我正在尝试使用Entity Framework Core构建电话列表。每当我尝试运行推荐时:Add-Migration "Initial"

我收到以下错误:Unable to determine the relationship represented by navigation property 'Member.MemberTeam' of type 'Team'. Either manually configure the relationship, or ignore this property from the model.

以下是我的模特:

public class Member {
        public int Id { get; set; }
        public string MemberName { get; set; }
        public string MemberTitle { get; set; }
        public Member MemberSupervisor { get; set; }
        public Team MemberTeam { get; set; }
    }

public class Team {
    public int Id { get; set; }
    public string TeamName { get; set; }
    public Member TeamSupervisor { get; set; }
    public ICollection<Member> TeamMembers { get; set; }
}

有什么建议吗?

1 个答案:

答案 0 :(得分:3)

TeamMember以及MemberMember之间存在多种关系。如果你只有这个型号......

public class Member
{
    public int Id { get; set; }
    public string MemberName { get; set; }
    public string MemberTitle { get; set; }
    public Team MemberTeam { get; set; }
}
public class Team
{
    public int Id { get; set; }
    public string TeamName { get; set; }
    public ICollection<Member> TeamMembers { get; set; }
}

...... EF不需要任何帮助。它会理解Team.TeamMembersMember.MemberTeam是一个关联的两端。

现在,如果你只添加......

public Member TeamSupervisor { get; set; }

... EF必须选择这是与MemberTeam的一对一关联的反向结束,还是除了一对多关联之外的新关联。但是,EF不会为您选择,您必须明确地通过映射关联来明确指示它。例如(在DbContext子类中):

protected override void OnModelCreating(ModelBuilder mb)
{
    mb.Entity<Team>().Property(a => a.Id).UseSqlServerIdentityColumn();
    mb.Entity<Team>().HasMany(t => t.TeamMembers).WithOne(m => m.MemberTeam);
    mb.Entity<Team>().HasOne(t => t.TeamSupervisor).WithMany()
                     .HasForeignKey("SupervisorId");

    mb.Entity<Member>().Property(a => a.Id).UseSqlServerIdentityColumn();
    mb.Entity<Member>().HasOne(m => m.MemberSupervisor).WithMany()
                       .HasForeignKey("SupervisorId");
}