I’m getting weird results from a query I thought I constructed correctly.
This query returns 2 values, which is correct:
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;
This query however, returns 4 values which is insanely incorrect since there are not 4 relations in the db! It returns all the possible roles. To me the query looks as if it should only return the records where the relation has both the correct userId and 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;
How should I construct the lambda-query?
I’ve not done this before but my guess is that you should do it like this: