Reputation: 2825
I have this SQL statement:
Select Id from dbo.AspNetUsers users Join AspNetUserRoles roles On roles.RoleId in ('2', '4', '5')
which I would like to convert to Linq.
The closest I could get to it was:
from users in db.AspNetUsers
join roles in db.AspNetUserRoles on new { RoleId = "2" } equals new { RoleId = roles.RoleId }
select new users.Id
which only joins on RoleId = "2"
, but I need it to join on RoleId = "4" and "5"
as well. Apparently the "in" keyword is not supported within a join statement in LINQ.
Is there a way to achieve equivalent behaviour in LINQ, possibly using different function syntax?
Upvotes: 0
Views: 40
Reputation: 32072
Rather than using a JOIN, use a WHERE on the navigation property.
I'll leave comments inline as it should be easier to understand.
string[] roles = new[] { "2", "4", "5" };
var users = db.AspNetUsers
// for each user
.Where(user => user.Roles // get the roles
// select the role id
.Select(role => role.RoleId)
// and filter by the wanted roles
.Where(role => roles.Contains(role))
// by ensuring any role with one of the wanted IDs exist
.Any())
// and then get the IDs of those users
.Select(user => user.UserId)
// to finally execute the query
.ToList();
Upvotes: 3