[英]Linq-to-SQL: How to perform a count on a sub-select
我仍在設法弄清楚如何正確使用LINQ-to-SQL,而不僅僅是編寫自己的存儲過程。
在代碼中,將一個userId傳遞到該方法中,然后LINQ使用它從與該userId匹配的GroupTable表中獲取所有行。 GroupUser表的主鍵是GroupUserId ,它是Group表中的外鍵。
/// <summary>
/// Return summary details about the groups a user belongs to
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public List<Group> GroupsForUser(int userId)
{
DataAccess.KINv2DataContext db = new DataAccess.KINv2DataContext();
List<Group> groups = new List<Group>();
groups = (from g in db.Groups
join gu in db.GroupUsers on g.GroupId equals gu.GroupId
where g.Active == true && gu.UserId == userId
select new Group
{
Name = g.Name,
CreatedOn = g.CreatedOn
}).ToList<Group>();
return groups;
}
}
這可以正常工作,但是我還想返回組中用戶的總數以及該組所有權下的聯系人總數。
偽代碼嗨!
/// <summary>
/// Return summary details about the groups a user belongs to
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public List<Group> GroupsForUser(int userId)
{
DataAccess.KINv2DataContext db = new DataAccess.KINv2DataContext();
List<Group> groups = new List<Group>();
groups = (from g in db.Groups
join gu in db.GroupUsers on g.GroupId equals gu.GroupId
where g.Active == true && gu.UserId == userId
select new Group
{
Name = g.Name,
CreatedOn = g.CreatedOn,
// ### This is the SQL I would write to get the data I want ###
MemberCount = ( SELECT COUNT(*) FROM GroupUser AS GU WHERE GU.GroupId = g.GroupId ),
ContactCount = ( SELECT COUNT(*) FROM Contact AS C WHERE C.OwnerGroupId = g.GroupId )
// ### End of extra code ###
}).ToList<Group>();
return groups;
}
}
我在SQL中寫的LINQ版本似乎可以解決問題,但我認為這行不通!
/// <summary>
/// Return summary details about the groups a user belongs to
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public static List<Group> GroupsForUser(int userId)
{
DataAccess.KINv2DataContext db = new DataAccess.KINv2DataContext();
List<Group> groups = new List<Group>();
groups = (from g in db.Groups
join gu in db.GroupUsers on g.GroupId equals gu.GroupId
where g.Active == true && gu.UserId == userId
select new Group
{
GroupId = g.GroupId,
Name = g.Name,
CreatedOn = g.CreatedOn,
ContactCount = (from c in db.Contacts where c.OwnerGroupId == g.GroupId select c).Count(),
MemberCount = (from guu in db.GroupUsers where guu.GroupId == g.GroupId
join u in db.Users on guu.UserId equals u.UserId
where u.Active == true
select gu ).Count()
}).ToList<Group>();
return groups;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.