[英]How to get all the users from an specific role
I got my Users
which is divided into two categories: Student
and Professor
, I'm trying to get all of the users within the Professor
role, but I don't know what I'm doing wrong. 我的Users
分为两类: Student
和Professor
,我试图使所有用户都处于“ Professor
角色内,但是我不知道自己在做什么错。
This is the code wherein I try to do that: 这是我尝试执行的代码:
RoleManager<IdentityRole> roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
List<IdentityUserRole> professors = roleManager.FindByName("Professor").Users.ToList();
List<AppUser> users = new List<AppUser>();
foreach(IdentityUserRole iuser in professors)
{
AppUser user = manager.FindById(iuser.UserId);
users.Add(user);
}
Professors
remains null for some reason. Professors
由于某种原因仍然无效。 Can anybody give me a hand? 有人可以帮我吗?
I doubt if it there is a built in function for this purpose already, but you can get users in this way: 我怀疑是否已经为此目的内置了功能,但是您可以通过这种方式获得用户:
public async Task GetUsersInRole()
{
ApplicationDbContext context = new ApplicationDbContext();
var roles = context.Roles.Where(r => r.Name == "Professor");
if (roles.Any())
{
var users = await UserManager.Users.ToListAsync();
var result = (from c in users
where c.Roles.Any(r => r.RoleId == roles.First().Id)
select c);
}
}
And call the method like this: 并调用如下方法:
public async Task<ActionResult> Index()
{
await GetUsersInRole();
return View();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.