我正在努力建立竞争。
我有以下模特:
public class Player
{
[Required]
public Guid PlayerId { get; set; }
[Required]
public string Firstname { get; set; }
[Required]
public string Lastname { get; set; }
}
public class Team
{
[Required]
public Guid TeamId { get; set; }
[Required]
public string TeamName { get; set; }
[Required]
[MaxLength(2)]
[ForeignKey("TeamPlayerFK")]
public List<Player> PlayersList { get; set; }
}
public class Match
{
[Required]
public Guid MatchId { get; set; }
[ForeignKey("MatchTeamFK")]
public Team Team { get; set; }
[ForeignKey("MatchPlayerFK")]
public Player Player { get; set; }
[Required]
public DateTime MatchDateTime { get; set; }
public int? Points { get; set; }
}
通过此设置,玩家只能在一个团队中。它应该能够加入多个团队。有人能帮助我朝正确的方向发展吗?
答案 0 :(得分:1)
这是我在@GertArnold帮助下找到的答案:
public class Player
{
[Required]
public Guid PlayerId { get; set; }
[Required]
public string Firstname { get; set; }
[Required]
public string Lastname { get; set; }
public virtual ICollection<TeamPlayer> TeamPlayers { get; set; }
public virtual ICollection<Match> Matches { get; set; }
}
public class Team
{
[Required]
public Guid TeamId { get; set; }
[Required]
public string TeamName { get; set; }
[Required]
public virtual ICollection<TeamPlayer> TeamPlayers { get; set; }
}
public class TeamPlayer
{
public Guid TeamPlayerId { get; set; }
public Guid TeamId { get; set; }
public Team Team { get; set; }
public Guid PlayerId { get; set; }
public Player Player { get; set; }
}
public class Match
{
[Required]
public Guid MatchId { get; set; }
public Guid TeamId { get; set; }
public Team Team { get; set; }
public Guid PlayerId { get; set; }
public Player Player { get; set; }
[Required]
public DateTime MatchDateTime { get; set; }
public int? Points { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<TeamPlayer>()
.HasOne(tp => tp.Team)
.WithMany(t => t.TeamPlayers)
.HasForeignKey(tp => tp.TeamId);
modelBuilder.Entity<TeamPlayer>()
.HasOne(tp => tp.Player)
.WithMany(p => p.TeamPlayers)
.HasForeignKey(tp => tp.PlayerId);
base.OnModelCreating(modelBuilder);
}