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

How to include relation with another entity, when using UserManager?


I'm using ASP Identity's UserManager to fetch users in particular roles.

var members = await _userManager.GetUsersInRoleAsync("Member");
var leaders = await _userManager.GetUsersInRoleAsync("Leader");

My problem is that my User entity has a relation to another entity. Normally I would do in the data context:

public async Task<IEnumerable<AppUser>> GetUsersAsync()
{
        return await _context.Users
            .Include(u => u.Projects)
            .Include(u => u.School)
            .ToListAsync();
}

But there is no Include method for UserManager. What would be the alternative here?


Solution

  • Just keep using the same syntax you posted for data context. But here use your original user list instead of taking users from context.

    public async Task<IEnumerable<AppUser>> GetUsersAsync()
    {
        return await _context.users
            .Include(u => u.Projects)
            .Include(u => u.School)
            .Where(u => members.Contains(m.Name)) //filter criteria...
            .ToListAsync();
    }
    

    This should get you all related entities from the existing users which you earlier got from userManager. UserManager is only a wrapper over the user store and it provides you with a different set of users as per role.