Filter role based users in c# linq

.net c# entity-framework-6 iqueryable linq

Question

we have multiple roles in our system and a user can have multiple roles assigned to it and everything is managed custom. We are not using identity or so.

I am sending my api request with some roles like "guest", "admin". Api should only returns users having these roles

this is how I am filtering users List<string> roles -> this is a variable that have role names coming from front-end suppose "admin"

roles = "admin" -> but can have more roles

UserRoleMappings is navigation property that holds user id and role id combination to save roles of particular user

now while getting all users, I would like to filter them so that

query.Where(user => user.UserRoleMappings.Any(urm => roles.Contains(urm.UserRole.Name)));

This query is fetching users having roles "admin" + "guests" as I have applied contains. But i need users which only have "admin" role

beacuse

user

1  user1
2 user2

role
1 admin
2 guest

userMapping
1 1
1 2
2 1

Api should only return user2 but it is also returning user1. This methid should be generic and should work formultiple roles

Thanks & Regards

1
0
5/23/2019 9:24:50 AM

Popular Answer

If you need users that only have the admin role and no other roles you can do

var adminUsers = query
    .Where(user => user.UserRoleMappings.All(urm => urm.UserRole.Name == "admin"));

because if "all" of their roles are named "admin" it necessarily is the only role they have.

0
5/27/2019 8:49:57 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow