我想在sql命令中返回子查询结果的逗号分隔符。 如下:
Select [User].UserName,
(Select [Role].Name + ', '
From
Security.UserRole As UserRole
Inner Join
Security.[Role] As [Role]
On UserRole.RoleId = [Role].RoleId
Where UserRole.UserId = [User].UserId
For Xml Path('')
)
From Security.[User] As [User]
基本上每个用户都有多个角色,我想为每个用户以逗号分隔格式加载角色名称。
我有什么办法可以在LINQ中编写这个查询吗?
由于
答案 0 :(得分:0)
尝试代码
创建方法获取用户角色特定用户
Public String GetuserRoles(int userid)
{
string strroles="";
(from UserRole in Security.UserRole
join Role in Security.Role on UserRole.RoleId equals Role.RoleId
where UserRole.UserId==userid
select new
{
strs = Role.Name + ","
}).ToList().ForEach(c => strroles = strroles + c.strs);
return strroles;
}
编写Linq查询后:
var result=( from p in Security.User select new {
UserName=p.UserName,
Roles=GetuserRoles(p.UserId)
}).ToList();