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
you have to use select and Where, query.Select(user => user.UserRoleMappings.where(urm => roles.Contains(urm.UserRole.Name))).toList();
now your where clause will return only Matched Element
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.