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

dotnet core Identiry map IList<AppUser> to IList<UserDto>


I want to get a list of users with the coach role. my query handler is this:

namespace Application.Coach.Queries.CoachList
{
    public class CoachListQueryHandler : IRequestHandler<CoachListQuery, CoachListVm>
    {
        private readonly CoachDataContext _context;
        private readonly IMapper _mapper;
        private readonly UserManager<AppUser> _userManager;

        public CoachListQueryHandler(CoachDataContext context, IMapper mapper, UserManager<AppUser> userManager)
        {
            _context = context;
            _mapper = mapper;
            _userManager = userManager;
        }

        public async Task<CoachListVm> Handle(CoachListQuery request, CancellationToken cancellationToken)
        {
            var coaches = await _userManager.GetUsersInRoleAsync("Coach");
            if (coaches == null) throw new NotFoundException(nameof(Domain.Coach.Coach));

            return new CoachListVm
            {
                CoachList = coaches
            };
        }
    }
}

but I'm getting this error when I want to return CoachListVm:

CS0266 C# Cannot implicitly convert type to. An explicit conversion exists (are you missing a cast?)

this is the CoachListVm :

public class CoachListVm
    {
        public IList<CoachListDto> CoachList { get; set; }
    }

and this is my CoachListDto :

public class CoachListDto : IMapFrom<AppUser>
    {
        public string Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool IsApproved { get; set; }
        public ICollection<AppUserRole> UserRoles { get; set; }
        [Column(TypeName = "decimal(18,2)")] public decimal MinHourlyRate { get; set; }
        [Column(TypeName = "decimal(18,2)")] public decimal MaxHourlyRate { get; set; }

        public void Mapping(Profile profile)
        {
            profile.CreateMap<AppUser, CoachListDto>()
                .ForMember(d => d.IsApproved, opt => opt.MapFrom(s => s.Coach.IsApproved))
                .ForMember(d => d.MinHourlyRate, opt => opt.MapFrom(s => s.Coach.MinHourlyRate))
                .ForMember(d => d.MaxHourlyRate, opt => opt.MapFrom(s => s.Coach.MaxHourlyRate));
        }
    }

my question is how can I map coaches to CoachLitVm?


Solution

  • you need to add mapping before return like below

    public async Task<CoachListVm> Handle(CoachListQuery request, CancellationToken cancellationToken)
    {
        var appUsers = await _userManager.GetUsersInRoleAsync("Coach");
        if (appUsers == null) throw new NotFoundException(nameof(Domain.Coach.Coach));
        var coaches = _mapper.Map<IList<AppUser>, CoachListVm>(appUsers); //here what I mean
        
        return coaches;
    }