我需要使用 Asp.Net 身份找到所有不包含特定角色的用户。
到目前为止,我有这样的东西,但它不起作用。
(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)
这给了我一个所有用户的列表,但它包括角色"SomeRole"中的用户。
看起来我需要某种类型的不在子查询中?
这是有效的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')
好吧,我有一个可行的解决方案,但它并不漂亮,我相信它可以写得更好。
(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()
在 c# 中,您可以获取不具有特定角色的所有用户,如下所示:
var role = context.Roles.SingleOrDefault(m => m.Name == "role");
var usersNotInRole = context.Users.Where(m => m.Roles.All(r => r.RoleId != role.Id));
用户实体框架的联接
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();