Arifullah Irfann

Arifullah Irfann

  • 1.2k
  • 410
  • 24.1k

How to Get User List with Role From IdentityUser using .net core a

Sep 27 2022 10:16 AM

How to Get User List with Role From IdentityUser using .net core and AutoMapper

Hi I want to Get the Identity User List with Role using .NET core and Auto Mapper (Create Map)
Each User Have Only one Role, I want to Return the List With Each User Role, I am Using Auto Mapper To Map
This is the List I want to be Generated

| Display Name | User Name |        Email       | Role  |   Department   |
|:------------:|:---------:|:------------------:|:-----:|:--------------:|
| Admin        | Admin123  | [email protected] | Admin | System Defined |

This is the Query 

public async Task<Result<PagedList<AppUserDto>>> Handle(Query request, CancellationToken cancellationToken)
{

    var query = _context.Users.
    OrderByDescending(d => d.Id).ProjectTo<AppUserDto>(_mapper.ConfigurationProvider)
    .AsQueryable();

    return Result<PagedList<AppUserDto>>.Success(
        await PagedList<AppUserDto>.CreateAsync(query, request.Params.PageNumber, request.Params.PageSize)
    );
}
public class AppUserDto
{
    public string Id { get; set; }
    public string DisplayName { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
    public string DepartmentNameE { get; set; }
    public string RoleId { get; set; }
    public string RoleName { get; set; }
}

Mapping

CreateMap<AppUser, AppUserDto>()
           .ForMember(d => d.DepartmentNameE, o => o.MapFrom(s => s.FDSDepartments.DepartmentNameE));

App User Class

public class AppUser : IdentityUser
{
    public string DisplayName { get; set; }
    public int DepartmentID { get; set; }
    public virtual FDSDepartments FDSDepartments { get; set; }
}