Reputation: 57
I'm working on a controller in my project. I'm trying to do the following:
string role = "something";
var newRole = new IdentityRole();
newRole = _DbContext.Roles.Where(r => r.Name == role).FirstOrDefault().;
user.Roles.Add(newRole);
Apparently, user.Roles.Add() only takes a IdentityUserRole as a parameter, but newRole is of type IdentityRole. How can I convert from one to the other? Is there an alternate way to accomplish what I want to do?
Explicitly casting doesn't work.
Upvotes: 1
Views: 2935
Reputation: 76557
Consider Using A UserManager
Generally, you would use the AddToRoleAsync()
method from UserManager
object to handle assigning roles to your users as opposed to adding them directly on the user object itself.
// Example of instantiating the User Manager
private readonly UserManager<ApplicationUser> _userManager;
public AccountController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
// Example of adding a user to a given role
public void AddUserToRole(string userId, string role)
{
var user = _userManager.FindByIdAsync(userId);
if (user != null)
{
await _userManager.AddToRoleAsync(user, role);
}
}
The UserManager class is responsible for ensuring that any relationships or information about your users is properly created, updated, and persisted as necessary, so it's generally preferred to delegate these type of responsibilities to it.
Regarding Direct Conversions
With regards to a direct conversion, you could use an approach similar to DavidG's response and simply use the Id from the User and the Role to build an object and add it to the user.
Upvotes: 2
Reputation: 118947
The IdentityUserRole
object is there to link a user to a role, you just need to create a new instance of it. You also need the ID of the role you are adding, for example:
var roleName = "something";
var role = _DbContext.Roles.Single(r => r.Name == roleName);
var userRole = new IdentityUserRole
{
UserId = user.Id,
RoleId = role.Id
};
user.Roles.Add(userRole);
However, you should really be using the UserManager
class for this. It has an AddToRoleAsync
method that handles this for you.
If you really don't want to use the async method though, there are non-async extensions available. https://msdn.microsoft.com/en-us/library/dn497483(v=vs.108).aspx
Upvotes: 1