【问题标题】:LINQ Lamba Join with CountLINQ Lambda 加入计数
【发布时间】:2018-10-21 22:27:04
【问题描述】:

我希望得到所有没有当前球队的球队,并得到所有有 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();

但我不能指望有多少球员拥有球队。怎么做?哪个是 SQL 中的查询? 感谢您的帮助!

编辑: 根据需要,类(从 DBFirst 生成):

【问题讨论】:

  • 你没有导航属性?
  • 你能提供球员和球队课程吗?
  • @DarjanBogdan 添加。没有蒂姆,任何导航属性谢谢
  • @MicheleBoscagin:我很确定Player.IdTeamTeam.Id 上没有外键。修复该问题,Entity-Framework 将添加此导航属性。

标签: c# .net linq


【解决方案1】:

基于上面的类,你可以扩展Team类并添加Players导航属性。

添加导航属性时,请确保 TeamPlayer 表之间存在数据库关系。此外,如果需要,请配置您的 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)

【讨论】:

  • 我猜没有外键,这就是实体框架没有自动创建的原因。
  • @TimSchmelter 是的,可能就是这样
【解决方案2】:

试试 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();

【讨论】:

    【解决方案3】:

    试试这个:

    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);
    

    【讨论】:

      【解决方案4】:

      这个怎么样?

      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();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多