.Net Core 3 AutoMapperMappingException:缺少类型映射配置或不支持的映射

.Net Core 3 AutoMapperMappingException: Missing type map configuration or unsupported mapping

以下是我在 startUp.cs

中设置自动映射器的方法
  public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        services.AddDbContext<BikeStoreContext>(
        options => options.UseSqlServer(Configuration.GetConnectionString("bikeStore")));
        services.AddScoped<ICustomerRepository, CustomerRepository>();

        services.AddAutoMapper(typeof(CustomerProfile));

    }

profile.cs

   public class CustomerProfile : Profile
    {
        public CustomerProfile()
        {
            CreateMap<Customer,CustomerDto>();
            CreateMap<CustomerDto, Customer>();
        }
    }

CustomerDto.cs

    public class CustomerDto
    {
        public int CustomerId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }
        public string Street { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string ZipCode { get; set; }
    }
}

这是我存储库中的 getCustomers 函数

 public async Task<IEnumerable<Customer>> GetCustomers()
    {
        return await _context.Customers.ToListAsync();
    }

我在控制器中使用 autoMapper,如下所示

[HttpGet]
    public async Task<IActionResult> GetAsync ()
    {
        var result = await _repo.GetCustomers();
        return Ok(_mapper.Map<CustomerDto>(result));
    }

尝试将 Customer 映射到 CustomerDto 时出现以下错误

AutoMapperMappingException: Missing type map configuration or unsupported mapping.

我尝试如下更改 startUp.cs 中的配置,但没有成功。

    var mapperConfig = new MapperConfiguration(mc =>
    {
        mc.AddProfile(new CustomerProfile());
    });

    IMapper mapper = mapperConfig.CreateMapper();
    services.AddSingleton(mapper);
    
  

我做错了什么?

存储库 returns IEnumerable<Customer> 并且您正试图将其映射到单个 CustomerDTO,您需要映射到集合,例如 List 或只是另一个 IEnumerable:

return Ok(_mapper.Map<List<CustomerDto>>(result));