在身份2获取用户的列表及其分配的角色 [英] Getting a list of users with their assigned role in Identity 2

查看:119
本文介绍了在身份2获取用户的列表及其分配的角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我坚持试图让这个输​​出

I am stuck trying to get this output

Id | Name   | Role
----------------------------
1  | John   | Administrator
----------------------------
2  | Mary   | Manager
----------------------------
3  | Sage   | Editor
----------------------------
4  | Hank   | Manager

我可以使它在LINQPad工作,但不知何故,我无法把它翻译为ASP.NET MVC。

I can make it work in LINQPad, but somehow I am unable to translate it to 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,
}

我如何MVC 5 LINQ在ASP.NET与身份?

How do I LINQ that in ASP.NET MVC 5 with Identity?

只是要清楚,我正在寻找用户和角色之间的联接查询。

Just to be clear, I am looking for the JOIN query between Users and Roles.

推荐答案

如果您使用的是ASP.NET身份2,你有一些codeS添加到AccountContoller。添加的ActionResult 获得的UserList 。您也NEDD ApplicationDbContext 实例,并从 OwinContext 得到它:

If you are using ASP.NET Identity 2, you have to add some codes to AccountContoller. Add an ActionResult to get UserList. You also nedd ApplicationDbContext instance and get it from 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,
                        Role = r.Name,
                    };

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

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

Update - if user has multiple roles:

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

这篇关于在身份2获取用户的列表及其分配的角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆