Why is my Action in Asp.Net Mvc code crashing when I want to get current user Role Name, when I want to edit user profile? This code is crashing
model.ApplicationRoleId = roleManager.Roles.Single(r => r.Name == userManager.GetRolesAsync(user).Result.Single()).Id;
Error message I get is : 500 (Internal Server Error)
Here is my EditUserview
public class EditUserViewModel
{
public string Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public List<SelectListItem> ApplicationRoles { get; set; }
public string ApplicationRoleId { get; set; }
public List<SelectListItem> DepartmentNames { get; set; }
public int DeptId { get; set; } // I have DeptId too in my AspNetUser table
}
And my Edituser action
[HttpGet]
public async Task<IActionResult> EditUser(string id)
{
EditUserViewModel model = new EditUserViewModel();
model.ApplicationRoles = roleManager.Roles.Select(r => new SelectListItem
{
Text = r.Name,
Value = r.Id
}).ToList();
model.DepartmentNames = context.Departments.Select(s => new SelectListItem
{
Text = s.DeptName,
Value = s.DeptId.ToString()
}).ToList();
if (!String.IsNullOrEmpty(id))
{
ApplicationUser user = await userManager.FindByIdAsync(id);
if (user != null)
{
model.Name = user.Name;
model.Email = user.Email;
model.DeptId = user.DepartmentId;
//model.ApplicationRoleId crashing
model.ApplicationRoleId = roleManager.Roles.Single(r => r.Name == userManager.GetRolesAsync(user).Result.Single()).Id; // Here crashing .. I don't know why.. Server 500 error
ViewBag.RoleId = new SelectList(RoleManager.Roles, "Id", "Name", model.ApplicationRoleId);
ViewBag.DeptId = new SelectList(db.Departments, "Deptd", "DeptName", model.DeptId);
}
}
return PartialView("_EditUser", model);
}
I tried like this but even this crashing ..
string existingRole = UserManager.GetRolesAsync(user.Id).Result.Single();// This crashing
then to put here :
string existingRoleId = RoleManager.Roles.Single(r => r.Name == existingRole).Id;
but string existingRole didn't work for me..
I would be greateful for any help..