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, }如何在 ASP.NET MVC 5 中使用 Identity 進行 LINQ?
為了清楚起見,我正在尋找使用者和角色之間的 JOIN 查詢。
如果您使用的是 ASP.NET Identity 2,則必須向 AccountContoller 添加一些程式碼。添加一個
ActionResult以獲得UserList. 您還 neddApplicationDbContext實例並從以下位置獲取它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); } . . . }更新- 如果使用者有多個角色:
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) }