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

时间:2018-04-02 06:35:15

标签: asp.net asp.net-identity asp.net-core-2.0 asp.net-roles

以下代码让我错误。

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

        }

1 个答案:

答案 0 :(得分:1)

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

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