Dynamic Linq with IN List

210 Views Asked by At

I am using EF Dynamic Linq library to construct dynamic queries based on user input.

I was able to set the where clause like this to search for User Roles = 1:

            var users = await _db.Users.Include(x => x.UserRoles).ThenInclude(x => x.Role)
            .Where(x => x.IsActive == true) 
            .Where("x => x.UserRoles.Any(y => y.RoleId == 1)")

In this query, the role id "1" was coming from another source, like a user input. How do I modify this query to search for multiple role ids? The incoming string value would be like "1,2,4". How do I use this string with my search to find all users with ANY of the roles? I tried to use something like new []{1,2,4} but not sure how to put this in the string.

1

There are 1 best solutions below

2
On
int[] roles = new int[] { 1, 2, 3 };
IEnumerable<User> users = await db.Users
    .Include(x => x.UserRoles)
    .ThenInclude(x => x.Role)
    .Where(x => x.IsActive == true && x.UserRoles.Any(y => roles.Contains(y)));