我正在尝试使用两个引用另一个模型的模型。
我已经研究过这个错误,但是看过有关以前.Net Core版本的建议。
以下是模型
public class Match
{
public int ID { get; set; }
public DateTime MatchDateTime
{ get; set; }
public int LocationID { get; set; }
public int GroupID { get; set; }
public int HomeTeamScore { get; set; }
public int AwayTeamScore { get; set; }
[Required]
public int HomeTeamID { get; set; }
public int AwayTeamID { get; set; }
public Location Location { get; set; }
public Group Group { get; set; }
[Required]
[ForeignKey("HomeTeamID")]
public Team HomeTeam { get; set; }
[ForeignKey("AwayTeamID")]
public Team AwayTeam { get; set; }
}
运行迁移后,我收到此错误:
介绍FOREIGN KEY约束' FK_Matches_Teams_AwayTeamID'在桌子上'比赛'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。
答案 0 :(得分:1)
当您运行Add-Migration
时,它将生成类似于以下代码的迁移文件。
migrationBuilder.CreateTable(
name: "Match",
columns: table => new
{
ID = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
AwayTeamID = table.Column<int>(nullable: false),
AwayTeamScore = table.Column<int>(nullable: false),
GroupID = table.Column<int>(nullable: false),
HomeTeamID = table.Column<int>(nullable: false),
HomeTeamScore = table.Column<int>(nullable: false),
LocationID = table.Column<int>(nullable: false),
MatchDateTime = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Match", x => x.ID);
table.ForeignKey(
name: "FK_Match_Team_AwayTeamID",
column: x => x.AwayTeamID,
principalTable: "Team",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Match_Team_HomeTeamID",
column: x => x.HomeTeamID,
principalTable: "Team",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
为ReferentialAction.NoAction
设置FK_Match_Team_HomeTeamID
。
答案 1 :(得分:0)
所以..解决方案很简单。
我将外键ID设为可空。我不确定是否可以同时使用nullable&#39;
请参阅以下代码:
public class Match
{
public int ID { get; set; }
public DateTime MatchDateTime
{ get; set; }
public int LocationID { get; set; }
public int GroupID { get; set; }
public int HomeTeamScore { get; set; }
public int AwayTeamScore { get; set; }
public int? HomeTeamID { get; set; }
public int? AwayTeamID { get; set; }
public Location Location { get; set; }
public Group Group { get; set; }
[Required]
[ForeignKey("HomeTeamID")]
public Team HomeTeam { get; set; }
[ForeignKey("AwayTeamID")]
public Team AwayTeam { get; set; }
}