Search code examples
linqasp.net-coreentity-framework-coreasp.net-core-identity

Create a list of Identity Registered Users using AspNetCore.Identity


I'm trying to construct a list of registered users for selection as a dropdown list in an application that will assign tasks to people (eventually with email integration). I have successfully made working use of AspNetCore.Identity for creating registered users.

Here is an example of what I've tried so far:

public class MinutaDbContext : IdentityDbContext<User>
{
    public List<User> QueryUserNames()
    {
        var context = new MinutaDbContext();
        var allUsers = context.Users.ToList();
        return allUsers;
    }
}

Controller:

public UserAssignmentController(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
    {
        UserManager = userManager;
        RoleManager = roleManager;
    }

The responses I've seen regarding UserManager with AspNet.Identity solutions don't work because it has a different declaration in AspNetCore and i'm unsure how to satisfy the required arguments for the above.

Is Linq required or is it possible to extract a list from:

public UserManager(IUserStore<TUser> store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<TUser> passwordHasher, IEnumerable<IUserValidator<TUser>> userValidators, IEnumerable<IPasswordValidator<TUser>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<TUser>> logger);

Or should I be looking elsewhere, such as the IQueryableUserStore Interface?

Update My DbContext constructor already extends base with argument option.

public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddSingleton(Configuration); // Injections
        services.AddSingleton<IGreeter, Greeter>();
        services.AddScoped<INoteData, SqlNoteData>();
        services.AddDbContext<MinutaDbContext>(options => 
                options.UseSqlServer(Configuration.GetConnectionString("Minuta")));
        services.AddIdentity<User, IdentityRole>()
            .AddEntityFrameworkStores<MinutaDbContext>();
    }

Solution

  • It's better to inject UserManager into your controller, then you can use Users property to get all users from the database:

    public UserAssignmentController : Controller
    {
        private readonly UserManager<User> _userManager;
    
        public UserAssignmentController(UserManager<User> userManager)
        {
            _userManager = userManager;
        }
    
         public async Task<IActionResult> Index()
        {
            var users = await _userManager.Users;
            return View(users);
        }
    }