如何根据实体框架6中的角色获取用户列表

时间:2016-01-09 13:12:49

标签: asp.net-mvc-5 entity-framework-6

我使用MVC5 EntityFramework 6

我有一个包含用户列表的诊所应用程序,每个用户都有帐户角色(医生,护士,实验室)

如何创建(医生)或(护士)或(实验室)

的DropDownList

默认情况下预定义所有用户和角色(个人用户帐户)

用户是(ApplicationUser) 角色是(IdentityRole) 我将表名称更新为Video

所有用户都位于同一个表格中Users所有角色都在Roles中,我在UserRoles

中将它们合并在一起

2 个答案:

答案 0 :(得分:0)

假设您的下拉数据是id&值对,那么你只需要选择一个不同的查询 - 但返回相同的类型 - 取决于所需的数据。

例如

IEnumerable<KeyValuePair<int, string>> GetNames(NameType nt) {

  if (nt == NameType.Nurse) {
    return from n in db.Nurses
           select new KeyValuePair {
             Key = n.Id,
             Value = n.Name
           };
  } else if (nt == NameType.Doctor) {
    return from d in db.Doctors
           select new KeyValuePair {
             Key = d.Id,
             Value = d.ProfessionalDisplayName
           };
  }

  [...]

}

您当然可以使用自定义类型(包括匿名:同一个程序集中具有相同成员(名称和值)的所有匿名类型在同一顺序中是相同的类型);并编码id中人物的类型(例如,单独保存跟踪)。

答案 1 :(得分:0)

使用以下代码

解决 控制器中的

string DoctorRoleID = roleManager.FindByName("Doctor").Id;
ViewBag.DoctorID = new SelectList(db.Users.Where(u => u.Roles.Any(r => r.RoleId == DoctorRoleID)).ToList(), "Id", "Email");

在视图中

<div class="form-group">
            <div class="col-md-2">
                @Html.LabelFor(model => model.DoctorID, "DOCTOR", htmlAttributes: new { @class = "control-label col-md-2" })
            </div>
            <div class="col-md-10">
                @Html.DropDownList("DoctorID", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.EndUserID, "", new { @class = "text-danger" })
            </div>
        </div>