我被困在试图得到这个输出
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?
解决方法
如果您使用的是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) }