0

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.

Franky
  • 1,262
  • 2
  • 16
  • 31

1 Answers1

1
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)));
Svyatoslav Danyliv
  • 21,911
  • 3
  • 16
  • 32
Nicholas Hunter
  • 1,791
  • 1
  • 11
  • 14
  • Sorry, I didn't make it clear, I had to use dynamic sql query due to the nature of user inputs. The string is dynamically constructed. – Franky Apr 05 '21 at 11:56
  • Ah ok I misread your question. Does this help? https://stackoverflow.com/questions/2455659/how-to-use-contains-or-like-in-a-dynamic-linq-query/2456070#2456070 – Nicholas Hunter Apr 05 '21 at 14:13