Search code examples
asp.net-mvcasp.net-identityasp.net-identity-2

ASP.Net identity, Users in role are always empty


I have implemented ASP.Net identity with some custom properties following this article -

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

Everything works well, except. I want to get users under specific role (e.g. Get me all the users under Admin role).

I tried following ways to retrieve the users -

            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));

Where _roleManager is of type ApplicationRoleManager : RoleManager<ApplicationRole>. _userManageris of type ApplicationUserManager : UserManager<ApplicationUser, string>.

I am unable to get Roles under user in _userManager and _userService

PS : _userService is service that extends IRepository which queries DbSet<ApplicationUser>.

I can see Roles being properly mapped in table ApplicationUserRoles and I get expected result when I do _userManager.IsInRole(user.Id, "Admin");.

What could've gone wrong with this?

Rahul.


Solution

  • I figured out where the issue was -

    Initially the table ApplicationUserRoles had only primary key definitions, not the foreign key mapping (many to many mapping)..

    I added this in 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);
    

    This completed the relationship and now I can see the Users under Roles and vice versa.

    This resulted issue while updating the database, however I just had to do some changes in migration -

    The object 'PK_Dbo.ApplicationUserRole' is dependent on column 'UserId'. ALTER TABLE DROP COLUMN UserId failed because one or more objects access this column.

    All I did is, I went to the migration file and moved these lines above DropColumn

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

    This solved the update-database exceptions as well.

    Rahul