【问题标题】:ASP.Net identity, Users in role are always emptyASP.Net 身份,角色中的用户始终为空
【发布时间】:2016-06-02 09:53:16
【问题描述】:

我已经在这篇文章之后使用一些自定义属性实现了 ASP.Net 身份 -

http://typecastexception.com/post/2014/06/22/ASPNET-Identity-20-Customizing-Users-and-Roles.aspx

一切都很好,除了。我想获取特定角色下的用户(例如,让我拥有管理员角色下的所有用户)。

我尝试了以下方法来检索用户 -

            var userRole = _roleManager.Roles.SingleOrDefault(m => m.Name == role.Name);
            var usersInRole = _userManager.Users.Where(m => m.Roles.Any(r => r.RoleId == userRole.Id));
            var usersInRole2 = _userService.GetUsers().Where(u => u.Roles.Any(r => r.RoleId == userRole.Id));

其中_roleManager 的类型为ApplicationRoleManager : RoleManager<ApplicationRole>_userManagerApplicationUserManager : UserManager<ApplicationUser, string>类型。

我无法在_userManager_userService 中获取用户下的角色

PS : _userService 是扩展查询 DbSet<ApplicationUser> 的 IRepository 的服务。

我可以看到角色在表 ApplicationUserRoles 中正确映射,当我执行 _userManager.IsInRole(user.Id, "Admin"); 时,我得到了预期的结果。

这可能出了什么问题?

拉胡尔。

【问题讨论】:

    标签: asp.net-mvc asp.net-identity asp.net-identity-2


    【解决方案1】:

    如果您使用的是实体框架,听起来您被延迟加载所吸引(因为角色被添加到数据库中,但不是在从可查询对象请求时)。

    尝试以下方法:

    _userManager.Users.Include(x => x.Roles).Where(m => m.Roles.Any(r => r.RoleId == userRole.Id));
    

    【讨论】:

      【解决方案2】:

      我发现问题出在哪里 -

      最初,ApplicationUserRoles 表只有主键定义,没有外键映射(多对多映射)..

      我在OnModelCreating添加了这个

      modelBuilder.Entity<ApplicationUserRole>().HasKey((ApplicationUserRole r) => new { UserId = r.UserId, RoleId = r.RoleId });
      
      //added these definitions
      modelBuilder.Entity<ApplicationUser>().HasMany(p => p.Roles).WithRequired().HasForeignKey(p => p.UserId);
      modelBuilder.Entity<ApplicationRole>().HasMany(p => p.Users).WithRequired().HasForeignKey(p => p.RoleId);
      

      这完成了关系,现在我可以在Roles 下看到Users,反之亦然。

      更新数据库时出现此问题,但我只需要在迁移中进行一些更改 -

      对象 'PK_Dbo.ApplicationUserRole' 依赖于列 '用户身份'。 ALTER TABLE DROP COLUMN UserId 失败,因为一个或多个 对象访问此列。

      我所做的只是,我去了迁移文件并将这些行移到DropColumn上方

      DropIndex("dbo.ApplicationUserRole", new[] { "ApplicationUser_Id" });
      DropIndex("dbo.ApplicationUserRole", new[] { "ApplicationRole_Id" });
      DropPrimaryKey("dbo.ApplicationUserRole");
      

      这也解决了update-database 异常。

      拉胡尔

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-05
        • 2014-07-22
        • 2017-07-25
        • 2014-02-05
        • 2021-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多