asp.netasp.net-identityasp.net-core-2.0asp.net-roles

Cannot convert from int to Project.Models.ApplicationUser


The below code gets me the error.

 _userManager.AddToRoleAsync(_userManager.FindByNameAsync(user.UserName).Id, "Employee");

I have included the code for further reference. I am trying to create a new user everytime the site is accessed and add a default role. User is properly added. Also I have previously seeded the roles, so roles exist.

public class ItemsController : Controller
  {
    private readonly MainContext _context;
    private readonly OtherContext _orcontext;
    private readonly IHostingEnvironment _appenv;
    private readonly UserManager<ApplicationUser> _userManager;
  }
    public ItemsController(MainContext context, OtherContext _orcontext, IHostingEnvironment appEnvironment, UserManager<ApplicationUser> userManager)
    {
        _context = context;
        _orcontext= orcontext;
        _appenv = appEnvironment;
        _userManager = userManager;
    }

    // GET: Items
    public async Task<IActionResult> Index()
    {
        var uname = User.Identity.Name.Remove(0, 5);
        if ((await _userManager.FindByNameAsync(uname)) == null)
        {
            ApplicationUser user = new ApplicationUser
            {
                UserName = uname
            };

            IdentityResult result = await _userManager.CreateAsync(user);
            _userManager.AddToRoleAsync(_userManager.FindByNameAsync(user.UserName).Id, "Employee");

        }

Solution

  • The first parameter to AddToRoleAsync is a user instance, not an id. Hence the error. In other words, remove the .Id bit.

    _userManager.AddToRoleAsync(_userManager.FindByNameAsync(user.UserName), "Employee");