需要将sql server查询更改为linq

时间:2014-11-05 14:54:10

标签: c# sql-server linq

select TeamName, [Description], COUNT(u.UserId)
from Team t
left outer join [User] u on u.TeamId=t.TeamId
group by TeamName, Description, UserId

这里我到目前为止但却无法做到这一点。请帮助

var countUser = (from t in db.Teams
                 join u in db.Users on u.TeamId equals t.TeamId
                 group TeamName, Description, UserId by select  
                 new
                 {
                     u.UserId
                 }).Count();

2 个答案:

答案 0 :(得分:1)

这应该这样做:

Teams.Join(Users.DefaultIfEmpty().
        t => t.TeamId,
        u => u.TeamId,
        (t, u) => new { t.TeamName, t.Description, UserId = u == null ? null:(int?)u.UserId })
    .GroupBy(x => x)
    .Select(g => new { g.Key.TeamName, g.Key.Description, Count = g.Count() });

答案 1 :(得分:0)

RePierre我会偷走你的部分答案(+1)因为我认为我理解OP在谈论什么,尽管问题文本没有传达它。

你可以这样做:

// Model class for View
public class UsersPerTeamCount
{
    public string TeamName { get; set; }
    public string Description { get; set; }
    public int Count { get; set; }
}

// ...

public ActionResult PlayersPerTeam()
{
    var model = from t in db.Teams
                    join u in db.Users on t.TeamId equals u.TeamId into joinedRecords
                    select new UsersPerTeamCount()
                    {
                        Name = t.TeamName,
                        Description = t.Description,
                        PlayerCount = joinedRecords.Count()
                    };

    return View(model);
}

至于OP评论"请尝试写作..."这只是语法上的差异,你编写它的方式并不重要 - 无论是流利还是查询语法(至少我认为它被称为查询语法)