问题:
一位初学者在学习实体框架代码优先的复杂性时,寻求指导,以定义一个有效的模型来反映团队和比赛之间的关系。具体要求是每场比赛都涉及两个不同的团队实体,分别指定为主队和客队,并保留比赛结果。
解答:
可以使用以下方法构建所需的模型:
重新定义团队类属性:
<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中文网其他相关文章!