LINQ using multiple role names while searching AD

John Zeen 21 Reputation points
2021-09-25T00:48:10.807+00:00

Hello,

I need to ensure that I only get a user who is a part of one of the roles using linq but not sure how to provide a list of roles in the query. For example my requirement is to only get a user who is a part of either admin or custadmin role. Most of the examples I see have something like this for checking one role only:

var roleId = context.Roles.Where(m => m.Name == "admin").Select(m => m.Id).SingleOrDefault();

var users = context.Users
.Where(u => u.Roles.Any(r => r.RoleId == roleId)).ToList();

Thanks
John

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,542 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Yijing Sun-MSFT 7,086 Reputation points
    2021-09-27T06:24:05.093+00:00

    Hi @John Zeen ,
    I think you could use the language specific OR condition.Just like this:

    var roleId = context.Roles.Where(m => m.Name == "admin"|| m.Name=="custadmin").Select(m => m.Id).SingleOrDefault();  
    

    Best regards,
    Yijing Sun


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our  documentation  to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.