gpt4 book ai didi

c# - Entity Framework 代码优先 - 来自同一张表的两个外键

转载 作者:IT王子 更新时间:2023-10-29 03:28:56 25 4
gpt4 key购买 nike

我刚开始使用 EF 代码,所以我是这个主题的初学者。

我想在 Teams 和 Matches 之间建立关系:

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; }
}

我得到一个异常(exception):

The referential relationship will result in a cyclical reference that is not allowed. [ Constraint name = 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 引用单个集合。匹配是在没有级联删除的情况下映射的,因为它在这些自引用多对多中不起作用。

关于c# - Entity Framework 代码优先 - 来自同一张表的两个外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5559043/

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