gpt4 book ai didi

c# - Entity Framework 核心一对多

转载 作者:行者123 更新时间:2023-12-04 02:09:16 27 4
gpt4 key购买 nike

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

我收到以下错误:无法确定由“团队”类型的导航属性“Member.MemberTeam”表示的关系。手动配置关系,或从模型中忽略此属性。

这是我的模型:

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 的一对一关联的反向端,还是一对多关联之外的新关联。但是,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");
}

关于c# - Entity Framework 核心一对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40268913/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com