需要将发布的sql查询转换为LINQ

时间:2017-06-29 08:22:31

标签: sql-server linq c#-4.0

如何在linq中进行查询请告知

select * 
from tblPermission 
where RoleId in (select roleid from tbluserrole where userid = @userID)

2 个答案:

答案 0 :(得分:0)

从SQL转换为LINQ时,按LINQ短语的顺序进行转换。如果您的SQL具有表别名,请将它们用作范围变量。如果查询包含子查询,请以相同方式首先翻译它。将IN翻译为Contains

var roles = from ur in tbluserrole where ur.userid == parmUserId select ur.RoleId;
var ans = from p in tblPermission
          where roles.Contains(p.RoleId)
          select p;

答案 1 :(得分:-1)

您可以通过两种方式执行此操作:

var roles = tbluserrole.Where(e => e.userid == userId).Select(e => e.roleid).ToList();
var prmsns = tblPermission.Where(e => roles.Contains(e.RoleId).ToList()

var prmsns = (from e in tblPermission 
    let roles = tbluserrole.Where(f => f.userid == userId).Select(f => 
f.roleid).ToList();
    where roles.Contains(e.RoleId)
    select e).ToList();

编辑:

你可以像这样使用内连接来做到这一点

var prmsns = (from e in tblPermission
    join f in tbluserrole on tblPermission.RoleId equals tbluserrole.roleid
    where f.userId == userId
    select e).ToList();