我很难尝试获得此输出
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,
}
如何使用Identity在ASP.NET MVC 5中LINQ呢?
为了清楚起见,我正在寻找用户和角色之间的JOIN查询。
答案 0 :(得分:9)
如果您使用的是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,
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)
}
答案 1 :(得分:0)
这将为您提供帮助
curl: (6) Could not resolve host: application; Name or service not known}