I have the following problem: I would like to create two tables in my database: 1. Team and 2. Match. The table representing a match has two foreign keys referencing the team table. I would like to have the deletion of a team from the team table set the corresponding records in the match table to NULL. Is such a solution possible with Entity Framework?
public class Team
{
public int Id { get; set; }
public string Faculty { get; set; }
public List<Player> Players { get; set; } = new List<Player>();
public List<Match> HomeMatches { get; set; } = new List<Match>();
public List<Match> VisitorMatches { get; set; } = new List<Match>();
}
public class Match
{
public int Id { get; set; }
public DateTime Date { get; set; }
public int? HomeTeamId { get; set; }
public virtual Team HomeTeam { get; set; }
public int? VisitorTeamId { get; set; }
public virtual Team VisitorTeam { get; set; }
public virtual Statistics Statistics { get; set; }
}
modelBuilder.Entity<Match>()
.HasOne(m => m.VisitorTeam)
.WithMany(t => t.VisitorMatches)
.HasForeignKey(m => m.VisitorTeamId)
.IsRequired(false)
.OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<Match>()
.HasOne(m => m.HomeTeam)
.WithMany(t => t.HomeMatches)
.HasForeignKey(m => m.HomeTeamId)
.IsRequired(false)
.OnDelete(DeleteBehavior.SetNull);
My previous solution generates an error:
Introducing FOREIGN KEY constraint 'FK_Match_Team_VisitorTeamId' on table 'Match' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
I tried modifying the cascading behavior, but without success - I'm still encountering errors. I have reviewed many forum posts, but none specifically address setting NULL values in this scenario.
2条答案
按热度按时间bkhjykvo1#
No, you can't do that even with SQL query -- will also fail when you create the second foreign key. It's violating 1NF. Ideally, you need to create the third table that holds Team ID and Match ID, i.e.
Then adjust the FKs as needed and you can just change the combination there.
1cosmwyk2#
Try to add:
.OnDelete(DeleteBehavior.Restrict)
for both relationships, like: