0

I have an ASP.Net Core application, and I'm using Microsoft identity, I'm trying to add a page to manage users roles, in the action result i defined a variable which contain user's information and it's all good but whenever i add the roles into this variable this error occurred(There is already an open Data Reader associated with this Connection which must be closed first.)

The highlighted line is caused the error and without it, everything works fine.

controller:

using CTS_System6.Models;
using CTS_System6.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CTS_System6.Controllers
{
    [Authorize(Roles ="Admin")]
    public class UsersController : Controller
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly RoleManager<IdentityRole> _roleManager;
        
        public UsersController(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
        {
            _userManager = userManager;
            _roleManager = roleManager;

        }
        public async Task<IActionResult> Index()
        {

            var users = await _userManager.Users.Select(user => new UserViewModel
            {
                Id = user.Id,
                FirstName = user.FirstName,
                LastName = user.LastName,
                Email = user.Email,
                //this is the line which cause the error message
                ***Roles = _userManager.GetRolesAsync(user).Result***
            }).ToListAsync();


            return View(users);
        }
    }
}
```[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/hkS8T.png
  • Does this answer your question? [Entity Framework,There is already an open DataReader associated with this Connection which must be closed first](https://stackoverflow.com/questions/43264526/entity-framework-there-is-already-an-open-datareader-associated-with-this-connec) – Fabiano May 13 '22 at 13:47
  • Don't use .Result! This line is bad: `_userManager.GetRolesAsync(user).Result`. You're in an async action method, so there's no excuse not to properly await your async method calls, ex: `await _userManager.GetRolesAsync(user)`. See [this video](https://www.youtube.com/watch?v=lQu-eBIIh-w) for a further explanation of why you shouldn't use .Result – mason May 13 '22 at 14:59
  • Hey, thanks for your answer, actually i can't use await inside the select that is why i user the keyword result to solve this issue. – Lighto Gamer May 13 '22 at 15:43

0 Answers0