简体   繁体   English

Asp.Net Identity 查找不在角色中的用户

[英]Asp.Net Identity find users not in role

I need to find all users that DONT'T contain a certain role, using Asp.Net Identity.我需要使用 Asp.Net Identity 找到所有不包含某个角色的用户。
So far I have something like this but it is not working.到目前为止,我有类似的东西,但它不起作用。

(From role In context.Roles
From userRoles In role.Users
Join us In context.Users On us.Id Equals userRoles.UserId
Where role.Name <> "SomeRole"
Select us.UserName) 

This give me a list of all users but it includes users in role "SomeRole".这给了我所有用户的列表,但它包括角色“SomeRole”的用户。
It looks I need some type of not in sub query?看起来我需要某种类型的 not in sub 查询?

Here is the SQL code that works but I would still like the LINQ query if possible.这是有效的 SQL 代码,但如果可能,我仍然希望使用 LINQ 查询。

select distinct A.UserName from AspNetUsers A
inner join AspNetUserRoles UR on UR.UserId = A.Id
inner join AspNetRoles R on R.Id = UR.RoleId
where not exists(
    select AspNetUserRoles UR1 on UR1.UserId = A.Id
    inner join AspNetRoles R1 on R1.Id = UR1.RoleId 
    where R1.Name = 'SomeRole')

Well I have a working solution but it is not pretty and I'm sure it can be written better.好吧,我有一个可行的解决方案,但它并不漂亮,我相信它可以写得更好。

(From role In context.Roles
From userRole In role.Users
Join user In context.Users On us.Id Equals userRole.UserId
Where Not (
    From role1 In context.Roles
    From userRole1 In role1.Users
    Join user1 In context.Users On user1.Id Equals userRoles1.UserId
    Where role1.Name = "SomeRole"
    Select user1.Id).Contains(user.Id)
Select user.UserName).Distinct()

In c# you can get all users that are not in a certain role like this:在 c# 中,您可以获取所有不属于特定角色的用户,如下所示:

var role = context.Roles.SingleOrDefault(m => m.Name == "role");
var usersNotInRole = context.Users.Where(m => m.Roles.All(r => r.RoleId != role.Id));

User Entity Framework's Join用户实体框架的加入

ApplicationRole superAdminRole = await _context.Roles.FirstOrDefaultAsync(x => x.Name == "SuperAdmin");

IEnumerable<ApplicationUser> users =await _context.UserRoles.Join(_context.Users, x => x.UserId, y => y.Id, (x, y) => new
{
    User = y,
    RoleId = x.RoleId
}).Where(x => x.RoleId != superAdminRole.Id)
  .Select(x => x.User)
  .ToListAsync();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM