Lambda中的子查询

时间:2014-12-04 12:29:09

标签: c# sql linq lambda

我正在

这是我尝试转换为

的sql server的查询
select * from Permission Where PermissionId in(select PermissionId from RoleDetail where RoleId =1)

这是我最初的lambda子查询

from p in Permissions
    let rde = from rd in RoleDetails
        select rd.PermissionId
        where p.PermissionId ==1
        select p

但它只显示了一个与该角色相关的记录,但实际上它有5个权限请帮助。

4 个答案:

答案 0 :(得分:2)

也许试试这个?而不是尝试使用.Contains(),只需在两个表上进行连接...

from p in Permissions
join rd in RoleDetails on p.PermissionId equals rd.PermissionId
where rd.RoleId == 1
select p;

答案 1 :(得分:1)

使用Join: -

var result = from p in Permissions
             join rd in RoleDetails.Where(x => x.RoleId == 1)
             on p.PermissionId equals rd.PermissionId 
             select p;

答案 2 :(得分:1)

你做错了这样做:

from p in Permissions
    let rde = (from rd in RoleDetails
               where rd.RoleId ==1
               select rd.PermissionId)
where p.PermissionId = rde
select p

请参阅LET usage HERE

答案 3 :(得分:1)

使用联接(在其他答案中提出)更好,但要修正您的查询,您应该在rde上过滤RoleId = 1,然后使用Permissions过滤rde:< / p>

from p in Permissions
    let rde = from rd in RoleDetails
        where rd.RoleId == 1           // filter RoleId = 1
        select rd.PermissionId
    where rde.Contains(p.PermissionId) // rde should contain p.PermissionId
    select p