Web API Queryable – how to apply AutoMapper?

Use the AutoMapper’s Queryable Extensions.

First, define the mapping.

// Old AutoMapper API
// Mapper.CreateMap<Person, PersonDto>();

// Current AutoMapper API
Mapper.Initialize(cfg => 
   cfg.CreateMap<Person, PersonDto>()
);

Then you can use something like this:

[EnableQuery]
public IQueryable<PersonDto> Get() {
    // Old AutoMapper API
    // return this.dbContext.Persons.Project().To<PersonDto>();

    // New AutoMapper API
    return this.dbContext.Persons.ProjectTo<PersonDto>();
}

Edit 04/2019: Updated to reflect current AutoMapper API.

Leave a Comment