Reputation: 478
I am trying to have a model with two references to another model.
I have researched this error, but have seen suggestions relating to previous .Net Core versions.
Below is the model
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; }
}
Upon running the migration, i get this error:
Introducing FOREIGN KEY constraint 'FK_Matches_Teams_AwayTeamID' on table 'Matches' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Upvotes: 1
Views: 4098
Reputation: 478
So..The solution was simple really.
I made the Foreign Key IDs nullable. I am not sure if making both nullable was 'required'
See the code below:
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; }
}
Upvotes: 1
Reputation: 1
When you run Add-Migration
, it will generate migration file similar to the below code.
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);
});
Set ReferentialAction.NoAction
for FK_Match_Team_HomeTeamID
.
Upvotes: 2