自动映射器:"Missing type map configuration or unsupported mapping."

Automapper: "Missing type map configuration or unsupported mapping."

我得到了一个 User 和一个 UserListDto。我正在尝试将我的 User 映射到 UserListDto

但是我得到了一个,

Missing type map configuration or unsupported mapping.

当我调用 GetUsers() 但不调用 GetUser(int id)

时有效

用户控制器:

    [HttpGet]
    public async Task<IActionResult> GetUsers()
    {
        var users = await _repo.GetUsers();

        var usersToReturn = _mapper.Map<IEnumerable<UserForListDto>>(users);

        return Ok(usersToReturn);
    }

    [HttpGet("{id}", Name = "GetUser")]
    public IActionResult GetUser(int id)
    {
        var user = _repo.GetUser(id, false);

        var userToReturn = _mapper.Map<UserForListDto>(user);

        return Ok(userToReturn);
    }

AutoMapper 配置文件:

public class AutoMapperProfiles : Profile
{
    public AutoMapperProfiles()
    {
        CreateMap<User, UserForListDto>();
        CreateMap<User, UserForDetailedDto>();
        CreateMap<UserForRegisterDto, User>();
        CreateMap<HighScoreDto, HighScore>()
        .ForMember(h=>h.TimeBetweenClicksAverage, 
        m=>m.MapFrom(u=>u.TimeBetweenClicksArray.Average()));
        CreateMap<HighScore,HighScoreForReturnDto>();



    }
}

用户:

public class User : IdentityUser<int>
{
    public virtual ICollection<UserRole> UserRoles { get; set; }
    public virtual ICollection<HighScore> HighScores { get; set; }
}

UserForDetailedDto:

public class UserForDetailedDto
{
    public int Id { get; set; }
    public string Username { get; set; }
}

您似乎正在尝试将单个 User 对象映射到 IEnumerable 集合。在您的 GetUser(int id) 方法中,尝试以这种方式将其映射到单个 UserForListDto 对象:

_mapper.Map<UserForListDto>(user)

看起来有两个问题:1) 您没有 await 调用 _repo.GetUser 和 2) 您试图将单个 User 映射到一个 IEnumerable<UserForListDto>.

确保 await _repo.GetUser 然后 _mapper.Map<UserForListDto>(user)

由于您没有等待 repo 调用,它正在尝试将类型 Task 映射到 UserListDto,这不是已配置的映射。