我刚开始使用 EF 代码,所以我完全是这个主题的初学者。
我想在团队和比赛之间建立关系:
1 场比赛 = 2 支球队(主队、客队)和结果。
我认为创建这样的模型很容易,所以我开始编码:
public class Team { [Key] public int TeamId { get; set;} public string Name { get; set; } public virtual ICollection<Match> Matches { get; set; } } public class Match { [Key] public int MatchId { get; set; } [ForeignKey("HomeTeam"), Column(Order = 0)] public int HomeTeamId { get; set; } [ForeignKey("GuestTeam"), Column(Order = 1)] public int GuestTeamId { get; set; } public float HomePoints { get; set; } public float GuestPoints { get; set; } public DateTime Date { get; set; } public virtual Team HomeTeam { get; set; } public virtual Team GuestTeam { get; set; } }
我得到一个例外:
引用关系将导致不允许的循环引用。[ 约束名称 = Match_GuestTeam ]
如何创建这样一个模型,同一个表有 2 个外键?
试试这个:
public class Team { public int TeamId { get; set;} public string Name { get; set; } public virtual ICollection<Match> HomeMatches { get; set; } public virtual ICollection<Match> AwayMatches { get; set; } } public class Match { public int MatchId { get; set; } public int HomeTeamId { get; set; } public int GuestTeamId { get; set; } public float HomePoints { get; set; } public float GuestPoints { get; set; } public DateTime Date { get; set; } public virtual Team HomeTeam { get; set; } public virtual Team GuestTeam { get; set; } } public class Context : DbContext { ... protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Match>() .HasRequired(m => m.HomeTeam) .WithMany(t => t.HomeMatches) .HasForeignKey(m => m.HomeTeamId) .WillCascadeOnDelete(false); modelBuilder.Entity<Match>() .HasRequired(m => m.GuestTeam) .WithMany(t => t.AwayMatches) .HasForeignKey(m => m.GuestTeamId) .WillCascadeOnDelete(false); } }
主键按默认约定映射。球队必须有两个比赛集合。您不能有两个 FK 引用的单个集合。匹配在没有级联删除的情况下进行映射,因为它在这些自引用多对多中不起作用。