2017-08-16 73 views
0

我得到了我的Users,它分爲兩類:StudentProfessor,我試圖讓Professor角色中的所有用戶,但我不知道是什麼我做錯了。如何獲得來自特定角色的所有用戶

這是代碼,其中,我試着這樣做:

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因爲某些原因保持爲空。 有人能幫我一下嗎?

回答

0

我懷疑它有一個內置的功能可實現此目的了,但你可以得到用戶通過這種方式:

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); 
    } 
} 

並調用這樣的方法:

public async Task<ActionResult> Index() 
{ 
    await GetUsersInRole(); 
    return View(); 
} 
+0

我只是試過了。我仍然收到一個空的json數組。 – RottenCheese

+0

我在郵遞員上的結果如下:[]。而且,我只是檢查了角色名拼寫正確。我甚至試圖通過id找到它,但同樣的事情發生。 – RottenCheese

+0

@RottenCheese你確定你的角色名是「教授」嗎? –

相關問題