我正在嘗試使用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; }
}

任何建議?

一般承認的答案

有幾個之間的關係, 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的一對一關聯的反向結束,還是除了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");
}


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因