問題:
一位初學者在學習實體框架代碼優先的複雜性時,尋求指導,以定義一個有效的模型來反映團隊和比賽之間的關係。具體要求是每場比賽都涉及兩個不同的團隊實體,分別指定為主隊和客隊,並保留比賽結果。
解答:
可以使用以下方法構建所需的模型:
重新定義團隊類屬性:
<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>
自定義外鍵關係:
[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>
注意:
This revised answer maintains the original image and uses more concise and clearer language while retaining the core information. The code examples are also formatted for better readability.
以上是如何首先在實體框架代碼中的同一表中與兩個外鍵建模團隊匹配關係?的詳細內容。更多資訊請關注PHP中文網其他相關文章!