asp.net-mvc – 获取在Identity 2中具有指定角色的用户列表

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 获取在Identity 2中具有指定角色的用户列表前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我被困在试图得到这个输出
Id | Name   | Role
----------------------------
1  | John   | Administrator
----------------------------
2  | Mary   | Manager
----------------------------
3  | Sage   | Editor
----------------------------
4  | Hank   | Manager

我可以使它在LINQPad中工作,但不知何故我无法将其转换为ASP.NET MVC.

from u in Users
from ur in u.Roles
join r in Roles on ur.RoleId equals r.Id
select new {
    Id = u.Id,Name = u.Name,Role = r.Name,}

我如何LINQ在ASP.NET MVC 5中使用Identity?

为了清楚起见,我正在寻找用户和角色之间的JOIN查询.

解决方法

如果您使用的是ASP.NET Identity 2,则必须向AccountContoller添加一些代码.添加ActionResult以获取UserList.您还需要ApplicationDbContext实例并从OwinContext获取它:
public class AccountController : Controller
{
    private ApplicationUserManager _userManager;
    private ApplicationSignInManager _signInManager;

    public AccountController(ApplicationUserManager userManager,ApplicationSignInManager signInManager)
    {
        UserManager = userManager;
        SignInManager = signInManager;
    }

    public ActionResult UserList()
    {
        var applicationDbContext = HttpContext.GetOwinContext().Get<ApplicationDbContext>();
        var users = from u in applicationDbContext.Users
                    from ur in u.Roles
                    join r in ApplicationDbContext.Roles on ur.RoleId equals r.Id
                    select new
                    {
                        u.Id,Name = u.UserName,};

            // users is anonymous type,map it to a Model 
            return View(users);
    }
    .
    .
    .
}

更新 – 如果用户有多个角色:

from user in applicationDbContext.Users
select new
{
    user.Id,user.UserName,Roles = applicationDbContext.Roles.Where(r => user.Roles.Select(ur => ur.RoleId).Contains(r.Id)).Select(r => r.Name)
}
原文链接:/aspnet/248617.html

猜你在找的asp.Net相关文章