How to get the role id from user role table in asp net

I have been trying to get the role id from Identity user role table. I can only get the role name using

var role = await _userManager.GetRolesAsync(user);

but I am stuck on how to get the role id.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

how to get the role id

You can try following code snippet.

var roleNames = await _userManager.GetRolesAsync(user);

var roleIds = _roleManager.Roles.Where(r => roleNames.AsEnumerable().Contains(r.Name)).Select(r => r.Id).ToList();

Test Result

How to get the role id from user role table in asp net

trying to get the role id from Identity user role table

If you’d like to query AspNetUserRoles table directly, you can try following approach.

Inject an instance of ApplicationDbContext

private readonly ApplicationDbContext _appdbcontext;

public HomeController(ILogger<HomeController> logger, ApplicationDbContext appdbcontext
    //...
    )
{
    _logger = logger;
    _appdbcontext = appdbcontext;
    //...
}

Query AspNetUserRoles table

var roleIds = _appdbcontext.UserRoles.Where(u => u.UserId == user.Id).Select(r => r.RoleId).ToList();

Method 2

You can do,

var roleIds = _userManager.FindById(User.Identity.GetUserId()).Roles.Select(r => r.RoleId);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x