How do I use automapper to map a list of identity users to a list dto?
I'm having difficulty getting my automapper to map a list of identity users to a dto. I pull the user list with a lengh > 0, but when I map it, it becomes an empty list. Here is my code.
startup.cs
public void ConfigureServices(IServiceCollection services)
{
var mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingProfile());
});
IMapper mapper = mappingConfig.CreateMapper();
services.AddSingleton(mapper);
}
MappingProfile.cs
public class MappingProfile : Profile
{
public MappingProfile()
{
// Add as many of these lines as you need to map your objects
CreateMap<User, userReponseDto>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id));
;
CreateMap<List<User>, IEnumerable<userReponseDto>>();
CreateMap<List<User>, List<userReponseDto>>();
}
}
userReponseDto.cs
public class userReponseDto
{
public string Id { get; set; }
public DateTimeOffset? LockoutEnd { get; set; }
//
// Summary:
// Gets or sets a flag indicating if two factor authentication is enabled for this
// user.
public bool TwoFactorEnabled { get; set; }
//
// Summary:
// Gets or sets a flag indicating if a user has confirmed their telephone address.
public bool PhoneNumberConfirmed { get; set; }
//
// Summary:
// Gets or sets a telephone number for the user.
public string PhoneNumber { get; set; }
//
// Summary:
// A random value that must change whenever a user is persisted to the store
public string ConcurrencyStamp { get; set; }
// Summary:
// Gets or sets a flag indicating if a user has confirmed their email address.
public bool EmailConfirmed { get; set; }
// Summary:
// Gets or sets the email address for this user.
public string Email { get; set; }
// Summary:
// Gets or sets the user name for this user.
public string UserName { get; set; }
// Summary:
// Gets or sets a flag indicating if the user could be locked out.
public bool LockoutEnabled { get; set; }
//
// Summary:
// Gets or sets the number of failed login attempts for the current user.
public int AccessFailedCount { get; set; }
}
User.cs
public class User : IdentityUser
{
}
ApplicationDbContext.cs
public DbSet<User> ApplicationUsers { get; set; }
UsersController.cs
public class UsersController : ControllerBase{
private readonly ApplicationDbContext _context;
private readonly IMapper _mapper;
public UsersController(IMapper mapper,ApplicationDbContext context)
{
_mapper = mapper;
_context = context;
}
[HttpPost]
public IActionResult GetUsers()
{
// return Ok(_context.ApplicationUsers.ToList());
var list = _context.ApplicationUsers.ToList();
IEnumerable<userReponseDto> userList ;
var response = _mapper.Map<List<userReponseDto>>(list);
// var response =
userList= list.Select(_mapper.Map<IdentityUser, userReponseDto>);
return Ok(userList);
}
}