When a beginner studys the complexity of the physical framework code, he sought guidance to define an effective model to reflect the relationship between the team and the game. The specific requirements are that each game involves two different team entities, which are specified as home teams and guest teams, and retain the results of the game.
Answer:
You can use the following methods to build the required model:
Rebcing the team class attributes:
Remove the ICOLLECTION property of the existing Matches from the Team class.
Introduce two new iCollection properties: Homematches and AwayMatches.<code class="language-csharp">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; } }</code>
Modify the MATCH class to contain the necessary key attributes, and remove the attribute from the Hometeam and Guestteam properties.
Use Fluent API in DBCONTEX to define the external key relationship:[ForeignKey]
<code class="language-csharp">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); } }</code>
Use Fluent API to define the external key relationship, because in this scene, the default agreed by the mapping main key is insufficient.
Disable the delete of the class to prevent accidental deleting the Teams referenced by multiple matches.The above is the detailed content of How to Model a Team-Match Relationship with Two Foreign Keys from the Same Table in Entity Framework Code First?. For more information, please follow other related articles on the PHP Chinese website!