无法从 int 转换为 Project.Models.ApplicationUser

Cannot convert from int to Project.Models.ApplicationUser

下面的代码让我得到了错误。

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

我已经包含了代码以供进一步参考。每次访问该站点时,我都试图创建一个新用户并添加一个默认角色。用户已正确添加。此外,我之前已经播种了角色,因此存在角色。

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");

        }

AddToRoleAsync 的第一个参数是用户 实例 ,而不是 ID。因此错误。换句话说,删除 .Id 位。

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