我想获取分配给某个角色的用户数量,如下所示,参见图片
我也检查了这篇文章,但没有帮助我。
我的角色视图模型
public class RolesViewModel
{
public RolesViewModel() { }
public RolesViewModel(ApplicationRole role)
{
Id = role.Id;
RoleName = role.Name;
}
public string Id { get; set; }
[Required]
[Display(Name = "Role Name")]
public string RoleName { get; set; }
public int Count { get; set; }
}
索引视图
@model IEnumerable<CMSRPPF.Areas.Admin.Models.RolesViewModel>
@{
ViewBag.Title = "Index";
Layout = "~/Areas/Admin/Views/Shared/_LayoutDashboard.cshtml";
}
<h2>Roles</h2>
<p>
@Html.ActionLink("Add Role", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.RoleName)
</th>
<th>
@Html.DisplayNameFor(model => model.Count)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.RoleName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Count)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
@Html.ActionLink("Details", "Details", new { id = item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
</table>
控制器
public ActionResult Index()
{
ApplicationDbContext db = new ApplicationDbContext();
List<RolesViewModel> list = new List<RolesViewModel>();
foreach (var role in RoleManager.Roles)
{
var r = new RolesViewModel(role)
{
RoleName = role.Name,
Count = db.Users.Where(x=>x.Roles.Select(roles => roles.RoleId).Contains("4738a87a-4461-4b54-828b-1c5543f13bb2")).ToList().Count()
};
list.Add(r);
}
return View(list);
}
到目前为止,我成功地根据特定角色的 RoleId 对用户进行了计数,但我不知道如何对所有用户执行此操作。如果有人可以帮助我,我将非常感激。
繁华开满天机
相关分类