通过Linq查询用户和角色(ASP.NET身份)

时间:2018-10-17 18:24:56

标签: c# asp.net-mvc entity-framework linq asp.net-identity

我想从数据库中获取患者和医生。我正在使用ASP.NET身份。

相关表格为AspNetUsersAspNetRolesAspNetUserRoles

这是我的查询:

var result = from pateints in context.Users
             let pEmail = pateints.Email
             from doctors in context.Users
             from roles in context.Roles
             where pateints.Roles.Any(r => r.RoleId == roles.Id && roles.Name == "Patient")
             where doctors.Roles.Any(r => r.RoleId == roles.Id && roles.Name == "Doctor") 
             select new { doctors.Email, pEmail };

我尽力找到了问题,但是此查询未返回任何内容。

2 个答案:

答案 0 :(得分:0)

您只需要加入所有三个实体,然后对角色名称应用过滤器,如下所示-

var result = from u in context.Users
             join ur context.UserRoles on u.Userid equal ur.Userid
             join r in context.Roles on r.Roleid equal ur.Roleid
             where r.Name == "Doctor" || r.Name == "Patient"
             select new {UserName = u.UserName, Email = u.Email, Role = r.Name };

示例输出如下-

UserName        Email           Role
abc xyz         abc@abc.com     Doctor
doc xyz         doc@abc.com     Doctor
pqr xyz         pqr@abc.com     Patient
lmn xyz         lmn@abc.com     Patient

答案 1 :(得分:0)

尝试一下

    using(ApplicationDbContext db=new ApplicationDbContext())
    {
          var users = (from user in db.Users
                       from roles in user.Roles
                       join role in db.Roles
                       on roles.RoleId equals role.Id 
                       select new
                       {
                           user.UserName, 
                           role.Name
                       }).ToList(); 
    }