C# API 测试错误:“AutoMapper.AutoMapperMappingException:缺少类型映射配置或不受支持的映射。”

问题描述 投票:0回答:1

我的特定 id 的 https get 方法工作得很好,但是返回列表的 get 方法却不能。我不明白如果它适用于需要 id 的方法,这怎么可能是一个映射器问题?

控制器方法:

 // GET: api/Hotels
    [HttpGet]
    public async Task<ActionResult<IEnumerable<HotelDto>>> GetHotels()
    {
        var hotels = _hotelsRepository.GetAllAsync();
        return Ok(_mapper.Map<List<HotelDto>>(hotels));
    }

    // GET: api/Hotels/5
    [HttpGet("{id}")]
    public async Task<ActionResult<HotelDto>> GetHotel(int id)
    {
        var hotel = await _hotelsRepository.GetAsync(id);

        if (hotel == null)
        {
            return NotFound();
        }

        return Ok(_mapper.Map<HotelDto>(hotel));
    }

自动映射器:

 public MapperConfig()
    {
        CreateMap<Country, CreateCountryDto>().ReverseMap();
        CreateMap<Country, GetCountriesDto>().ReverseMap();
        CreateMap<Country, GetCountryDto>().ReverseMap();
        CreateMap<Country, UpdateCountryDto>().ReverseMap();

        CreateMap<Hotel, HotelDto>().ReverseMap();
        CreateMap<Hotel, CreateHotelDto>().ReverseMap();
    }

详细的错误响应

AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping.

Mapping types:
AsyncStateMachineBox`1 -> List`1
System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[[System.Collections.Generic.List`1[[HotelListing.API.Data.Hotel, HotelListing.API, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=7.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[HotelListing.API.Repository.GenericRepository`1+<GetAllAsync>d__4[[HotelListing.API.Data.Hotel, HotelListing.API, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], HotelListing.API, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> System.Collections.Generic.List`1[[HotelListing.API.Models.Hotels.HotelDto, HotelListing.API, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]
c# .net rest
1个回答
2
投票

您忘记了

await
GetAllAsync
的结果,因此您尝试映射返回的
Task<List<Hotel>>
而不是所需的
List<Hotel>
(更准确地说是
Task
的继承者 -
AsyncStateMachineBox
)。尝试:

var hotels = await _hotelsRepository.GetAllAsync();
return Ok(_mapper.Map<List<HotelDto>>(hotels));
© www.soinside.com 2019 - 2024. All rights reserved.