我需要使用Asp.Net Identity找到所有不包含某个角色的用户。
到目前为止,我有类似的东西,但它不起作用。
(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)
这给了我一个包含所有用户的列表,但它包括角色中的用户&#34; SomeRole&#34;。
它看起来我需要一些不在子查询中的类型?
这是可行的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()
答案 0 :(得分:10)
在c#中,您可以获得所有不属于某个角色的用户:
var role = context.Roles.SingleOrDefault(m => m.Name == "role");
var usersNotInRole = context.Users.Where(m => m.Roles.All(r => r.RoleId != role.Id));
答案 1 :(得分:0)
用户实体框架的加入
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();