Reputation: 604
I am doing this to get roles of a user:
var roles = await _userManager.GetRolesAsync(user);
After that a simple loop through can serve the purpose like this:
foreach(var r in roles)
{
if (r.Name == "School")
{
}
}
Now, I am stuck in knowing what should be the property of object r. Can you answer this very basic stuff?
Upvotes: 2
Views: 1632
Reputation: 1212
When you get object
of Role
using Identity, you have List of object with many property like: User
,Id
, Name
, NormalizeName
, and something like this. You can trace and see those.
You have to know that what do you want.
If you want to check userRoles
with system Roles
you can write you code like:
var roles = await _roleManager.Roles.TolistAsync();
var userRolesName = await _userManagment.GetRolesAsync(user);
Now! you have list of roles that user have, and you have all roles.and with this code you get object of roles that user have like:
var userRoles = userRolesName.Where(x=>userRolesName.Contain(x.Name));
With this code you have object of Roles that user have.and you can process them.
Upvotes: 0
Reputation: 93153
UserManager<TUser>.GetRolesAsync(TUser)
returns a Task<IList<String>>
. In your example, you're using await
, which means your roles
variable becomes of type IList<String>
. When iterating through roles
with your foreach
statement, each r
value within the loop is simply of type String
. It's obvious that String
does not contain a property named Name
and as such, the error makes sense.
It appears you were expecting r
to represent a complex type (perhaps an IdentityRole
), but as it's simply a string here, you can just compare r
directly, like this:
foreach(var r in roles)
{
if (r == "School")
{
}
}
Upvotes: 1