Lambda表达式不正确

Phi*_*hil 3 c# linq entity-framework

我从我认为构造正确的查询得到了奇怪的结果.

此查询返回2个值,这是正确的:

int userId = GetUserId(); //Not exactly like this; simplified
var context = new Entities();
//Get the roles 
var relations = (from q in context.UserHasRole
                 where q.UserId == userId
                 select q).ToList();
List<Roles> roles = new List<Roles>();
foreach (var item in relations)
{
    Roles role = (from r in context.Roles
                  where r.Id == item.RoleId
                  select r).SingleOrDefault();
                  roles.Add(role);
 }
 return roles;
Run Code Online (Sandbox Code Playgroud)

但是,此查询返回4个值,这些值极其不正确,因为db中没有4个关系!它返回所有可能的角色.对我来说,查询看起来好像只应返回关系具有正确userId和roleId的记录.

            //Get the roles 
            var roles = (from q in context.Roles
                         where context.UserHasRole.Any(o => o.UserId == userId)
                         && context.UserHasRole.Any(p => p.RoleId == q.Id)
                         select q).ToList();

            return roles;
Run Code Online (Sandbox Code Playgroud)

我应该如何构造lambda查询?

Pau*_*aul 7

我之前没有这样做,但我的猜测是你应该这样做:

 //Get the roles 
 var roles = (from q in context.Roles
     where context.UserHasRole.Any(o => o.UserId == userId && o.RoleId == q.Id)
     select q).ToList();

 return roles;
Run Code Online (Sandbox Code Playgroud)