我有这个SQL查询(示例简化):
;WITH info as (
--actually a complex multi table query, just simplified
select UserID, RoleName
from UserRole
),
AccountUsers as
(
select distinct UserID
from info
)
select UserID,
Roles = STUFF(
(
SELECT ', ' + l.RoleName
FROM info AS l
WHERE l.UserID = au.UserID
FOR XML PATH(''), TYPE
).value('.[1]','nvarchar(max)'), 1, 2, '')
from AccountUsers au
是否可以将其转换为linq-to-sql以便生成单个查询?我有超过500个用户,可能有大约十几个角色。它不必生成相同的查询,只需要相同的结果。(在这里建立了一个sql的演示http://sqlfiddle.com/#!6/c54fc/4)
(编辑:添加了linq) 这是我生成的多个查询的linq:
var userroles = dc.UserRoles
.Select(ua => new
{
ua.UserID,
Roles = string.Join(", ",
dc.UserRoles
.Where(ur => ur.UserID == ua.UserID )
.Select(ur => ur.RoleName)
.Distinct())
});