Search code examples
c#asp.net-core.net-coreasp.net-core-mvcasp.net-core-identity

How To Add Role Id to Models


I have gotten the role id of the user and I want to update another model that contains a column for roleid but it always says can not convert generic list to string and I convert the gotten role id to string but do not get the value and I want to add it to the model.

This is what I have so far

var role = await _userManager.GetRolesAsync(user); 
var roleIds = _roleManager.Roles
    .Where(r => role.AsEnumerable().Contains(r.Name))
    .Select(r => r.Id)
    .ToList();

This is the exception code. When I change to ToString that do not get any value

var roleIds = _roleManager.Roles
    .Where(r => role.AsEnumerable().Contains(r.Name))
    .Select(r => r.Id)
    .ToString(); 

userEmployee.Stations.Add(new Models.AppModel.StaffStation { RoleId = roleIds })

     

And I only want to update not even create new. I am new to .net


Solution

  • continuous on Fabio's answer you can check if the user in the role before adding to your model as below

         //Get All User Roles
            var userRoles = roleManager.Roles.Where(r => role.AsEnumerable().Contains(r.Name));
    
            //Loop on All User Roles
            foreach (var userRole in userRoles)
            {
                //Check if User not in role so we will add it
                if(!await userManager.IsInRoleAsync(user, userRole.Name))
                {
                    var station = new Models.AppModel.StaffStation { RoleId = userRole.Id };
                    userEmployee.Stations.Add(station);
                }
                else
                {
                    //here you can check if you don't need this role for this user anymore so delete it
                    //or keep it as is
                }
                
            }