我希望让所有球队都没有当前的球队,并让所有球队拥有4名或更多球员。 我尝试编写这个linq lambda查询:
teams = connection.Team
.Join(connection.Player,
t => t.ID,
p => p.IDTeam,
(t, p) => new { Team = t, Player = p })
.Where(tp => tp.Player.IDTeam == tp.Team.ID
&& tp.Team.ID != team.ID
&& tp.Team.IsVisible == true
&& !tp.Team.DeleteDate.HasValue)
.Select(tp => tp.Team)
.ToList();
但我不能指望有多少球员拥有球队的条件。怎么做?对于info,SQL中的查询是哪个? 谢谢你的帮助!
答案 0 :(得分:3)
根据上述类,您可以扩展Team
类并添加Players
导航属性。
添加导航属性时,请确保 Team 和 Player 表之间存在数据库关系。此外,如果需要,请配置您的DbContext
。
public class Team
{
//...other properties
public virtual ICollection<Player> Players { get; set; }
}
当您添加导航属性时,实现您的要求将是微不足道的:
connection.Teams
.Where(t => t.ID != team.ID && t.IsVisible == true && !t.DeleteDate.HasValue && t.Players.Count() >= 4)
答案 1 :(得分:0)
尝试使用GroupBy():
var teams = (from tp in connection.Team
join p in connection.Team on tp.Player.IDTeam equals p.Team.ID
select new { Team = tp, Player = p })
.Where(tp => tp.Team.IsVisible == true && !tp.Team.DeleteDate.HasValue)
.GroupBy(x => x.Team.ID)
.Where(x => x.Count >= 4)
.ToList();
答案 2 :(得分:0)
试试这个:
teams = connection.Team
.Join(connection.Player,
t => t.ID,
p => p.IDTeam,
(t, p) => new { Team = t, Player = p })
.Where(tp => tp.Player.IDTeam == tp.Team.ID
&& tp.Team.ID != team.ID
&& tp.Team.IsVisible == true
&& !tp.Team.DeleteDate.HasValue)
.Select(tp => tp.Team)
.ToList().GroupBy(i=>i.ID).Where(i=>i.Count()>=4);
答案 3 :(得分:0)
这个怎么样?
var teams =
(from t in connection.Team
join p in connection.Player on p.TeamId equals t.ID into playersInTeam
select new
{
Team = t,
PlayersCount = playersInTeam.Count(x => x.TeamId == t.Id)
})
.Where(x => x.PlayersCount >= 4)
.ToList();