Search code examples
asp.net-coreasp.net-identityentity-framework-core

How to get ApplicationUser object for a given user


In my following action method I'm getting following design time error on line var result = await _userManager.AddToRoleAsync(user, "AdminRole");. But if I use var user = new ApplicationUser { UserName = model.SelectedUserName to get a user then the above line does not give design time error, however; as expected, it gives run time validation error as: User someUSerName already exist. I understand the run time error is due to the fact that I'm adding a role to an existing user but passing a new instance of it. Question: How can I get an existing user as an ApplicationUser object so I can pass it to AddToRoleAsync(....) below? I'm using ASP.NET Core 1.1.1, Individual User Accounts mode, VS2017.

Error:

Cannot convert from  Task<MyProj.Model.ApplicationUser> to MyProj.Model.ApplicationUser

Controller

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddUserToRole(RoleRelatedViewModel model, string returnUrl = null)
{
    ViewData["ReturnUrl"] = returnUrl;
    if (ModelState.IsValid)
    {
        var user = _userManager.FindByNameAsync(model.SelectedUserName); //cannot be used in AddToRoleAsync(user,"AdminRole") since FindByNameAsync returns Task<ApplicationUser>
        //var user = new ApplicationUser { UserName = model.SelectedUserName };
        var result = await _userManager.AddToRoleAsync(user, "AdminRole");
        if (result.Succeeded)
        {
            return RedirectToLocal(returnUrl);
        }
        AddErrors(result);
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

Solution

  • try var user = await _userManager.FindByNameAsync(model.SelectedUserName);

    it seems like AddToRoleAsync expects ApplicationUser as first parameter, but you giving Task So if you use await before FindByNameAsync call your user variable will be ApplicationUser.