Davis Miller
Davis Miller

Reputation: 59

ASP MVC Identity 2 get user in "User" role

I add user and assign role as below code, I user ASP MVC 5 identity and EF code first.

//some Code
                var result = manager.Create(insert, applicationUser.PasswordHash);
                IdentityResult result2 =null;
                if (result.Succeeded)
                {
                result2 = manager.AddToRole(insert.Id, "User");
}
//Some Code

So i need to show list of user with custom role in view like "User" role. i wrote this code :

    ApplicationDbContext myDbContext = new ApplicationDbContext();
    var getRoleId = myDbContext.Roles.Where(r => r.Name == "User").Select(m => m.Id).SingleOrDefault();
    var fetch = myDbContext.Users.Where(u => u.Roles.Any(r => r.RoleId.ToString() == getRoleId)).ToList();
    return View(fetch);

getRoleId value is "4", it is right , but fetch always count equal 0.I try more than 3 4 hours but i can not get result.Where is my wrong ? and what is the solution ? Thank you.

UPDATE : I found my problem in add role but i do not know how can fix that ! When adding the users to roles using the above, the users id is added to the UserId column of the UserRoles table, but there was a third column called IdentityUser_Id which was always null.

Out of curiosity I added my user id to that column as well and now the everything works. the application picked up my user role.

My follow up question to this is can I set the IdentityUser_Id automatically? using something similar to the UserManager.AddToRole() which adds the userId to both columns?

Upvotes: 0

Views: 788

Answers (1)

Sonal Borkar
Sonal Borkar

Reputation: 561

Why are you getting getRowId and not pull Users by Role Name? Try Below:

  var fetch = myDbContext.Users.Where(u => u.Roles.Any(r => r.Name == 
     "User")).ToList();

Upvotes: 1

Related Questions