linq中的子查询到sql

时间:2017-06-13 01:25:34

标签: linq tsql subquery

我想在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]

基本上每个用户都有多个角色,我想为每个用户以逗号分隔格式加载角色名称。

Sql中的结果集如下: enter image description here

我有什么办法可以在LINQ中编写这个查询吗?

由于

1 个答案:

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