我有3个表需要在一个表中组合。在下面你可以看到代码。
问题是每个球员都可以参加每场比赛的一个或多个球队。每场新赛事的球员和球队都会安排好。
那么我怎样才能用流畅的api映射它,或者有更好的方法来解决它。谢谢你们。
public class Player
{
public int PlayerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public DateTime TimeStamp { get; set; }
public ICollection<Team> Teams { get; set; }
public ICollection<Tournament> Tournaments { get; set; }
}
public class Team
{
public int TeamID { get; set; }
public string Name { get; set; }
public DateTime TimeStamp { get; set; }
public ICollection<Player> Players { get; set; }
public ICollection<Tournament> Tournaments { get; set; }
}
public class Tournament
{
public int TournamentID { get; set; }
public DateTime Date { get; set; }
public int PlaceID { get; set; }
public DateTime TimeStamp { get; set; }
public virtual Place Place { get; set; }
public ICollection<Player> Players { get; set; }
public ICollection<Team> Teams { get; set; }
}
public class BPContext : DbContext
{
public DbSet<Tournament> Tournaments { get; set; }
public DbSet<Place> Places { get; set; }
public DbSet<Table> Tables { get; set; }
public DbSet<Player> Players { get; set; }
public DbSet<Team> Teams { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
答案 0 :(得分:1)
我不知道你想用这个来完成什么。你有的桌子包含所有球员,所有球队和所有锦标赛。
我想会有一场比赛要打?你可以做的是创建另一个表匹配,使用类似这样的实体:
public class Match
{
[Key]
public int MatchId {get;set;}
[ForeignKey("Tournament")]
public int TournamentId {get;set;}
[InverseProperty("Matches")]
public virtual List<Team> Teams {get;set;}
[InverseProperty("Matches")]
public virtual List<Player> Players {get;set;}
[InverseProperty("Matches")]
public virtual Tournament Tournament {get;set;}
}
这个新实体拥有所有3个先前的实体。但是,您必须修改以前的更改才能包含这些更改:
public class Player
{
public int PlayerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public DateTime TimeStamp { get; set; }
[InverseProperty("Players")]
public virtual List<Match> Matches { get; set; }
[InverseProperty("Players")]
public virtual List<Team> Teams {get;set;}
}
可以使用LINQ:ctx.Players.Where(x =&gt; x.PlayerId == 15).Matches.Select(x =&gt; x.TournamentId)来完成玩家的所有锦标赛。
如果您想查看锦标赛中的所有玩家:ctx.Matches.Where(x =&gt; x.TournamentId == 15).Players.Select(x =&gt; x.Name)。
public class Team
{
public int TeamID { get; set; }
public string Name { get; set; }
public DateTime TimeStamp { get; set; }
[InverseProperty("Teams")]
public List<Match> Matches {get;set;}
[InverseProperty("Teams")]
public List<Player> Players {get;set;}
}
public class Tournament
{
public int TournamentID { get; set; }
public DateTime Date { get; set; }
public int PlaceID { get; set; }
public DateTime TimeStamp { get; set; }
public virtual Place Place { get; set; }
[InverseProperty("Tournament")]
public virtual List<Match> Matches {get;set;}
}