[英]Filter role based users in c# linq
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请求,其中包括“guest”,“admin”等角色。 Api should only returns users having these roles
Api应该只返回具有这些角色的用户
this is how I am filtering users List<string> roles
-> this is a variable that have role names coming from front-end suppose "admin" 这就是我如何过滤用户
List<string> roles
- >这是一个变量,其角色名称来自前端,假设为“admin”
roles = "admin" -> but can have more roles roles =“admin” - >但可以拥有更多角色
UserRoleMappings is navigation property that holds user id and role id combination to save roles of particular user UserRoleMappings是导航属性,用于保存用户ID和角色ID组合以保存特定用户的角色
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. 此查询正在获取具有“admin”+“guests”角色的用户,因为我已应用包含。 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. Api应该只返回user2,但它也返回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(); 你必须使用select和Where,query.Select(user => user.UserRoleMappings.where(urm => roles.Contains(urm.UserRole.Name)))。toList();
now your where clause will return only Matched Element 现在你的where子句只返回匹配元素
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. 因为如果他们的“所有”角色被命名为“admin”,那么它必然是他们唯一的角色。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.