本文首先解決了從同一表(例如,Team
)將兩個外鍵映射到實體框架代碼中的另一個表(Match
)的挑戰。 遇到的一個常見錯誤是周期性參考例外。
問題:
>用Match
HomeTeam
和aGuestTeam
進行建模時,都引用了Team
>表時,經常會出現週期性關係誤差。 這是因為默認情況下,實體框架假定一對多的關係,導致循環依賴性。
解決方案:
關鍵是將關係明確定義為兩個單獨的一對一對多關係,從Team
類中創建兩個導航屬性來實現的。 Match
Team
請注意,
現在有<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; } } 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; } }</code>>和
> collections,清楚地區分了每個團隊在比賽中的角色。 Team
>
HomeMatches
AwayMatches
模型配置(dbContext):
需要在您的類的方法中明確定義關係:
>
OnModelCreating
此配置明確映射外國鑰匙,重要的是,設置DbContext
以防止刪除匹配時的團隊意外刪除。
以上是如何首先在實體框架代碼中正確映射兩個外鍵?的詳細內容。更多資訊請關注PHP中文網其他相關文章!