Home >Backend Development >C++ >How to Handle Multiple Foreign Keys to the Same Table in Entity Framework Code First?
In Entity Framework Core, it is essential to model the inter -enthusiastic relationship. As you encounter, creating a model with multiple external keys in the same table may cause abnormalities.
In your example, you define the Team and MATCH entities to capture the relationship between the team and the game. One of them involves two teams, one home team and a guest team. However, your initial method will trigger the cycle reference abnormality.
In order to solve this problem, you must use the smooth API configuration of Hasrequired () and withmany () and the Withmany () method, as well as the Withmany () method and the onmodelcreating (). This is a updated model:
In this model:
<code class="language-c#">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(ModelBuilder modelBuilder) { modelBuilder.Entity<Match>() .HasOne(m => m.HomeTeam) .WithMany(t => t.HomeMatches) .HasForeignKey(m => m.HomeTeamId) .OnDelete(DeleteBehavior.Restrict); // or DeleteBehavior.NoAction modelBuilder.Entity<Match>() .HasOne(m => m.GuestTeam) .WithMany(t => t.AwayMatches) .HasForeignKey(m => m.GuestTeamId) .OnDelete(DeleteBehavior.Restrict); // or DeleteBehavior.NoAction } }</code>
Team entities include two competitions: Homematches and AwayMatches.
OnDelete(DeleteBehavior.Restrict)
DeleteBehavior.NoAction
. WillCascadeOnDelete(false)
will prevent deletion operations, unless the relevant records do not exist; OnDelete(DeleteBehavior.Restrict)
will ignore the deletion operation, depending on the behavior of the database providing program. Choose which one depends on your specific needs. OnDelete(DeleteBehavior.NoAction)
The above is the detailed content of How to Handle Multiple Foreign Keys to the Same Table in Entity Framework Code First?. For more information, please follow other related articles on the PHP Chinese website!