I have a problem executing my AutoMapper mappings when using OData with specific $select
or $expand
values.
Using the WebApi Action:
public IQueryable<BookInRequestDto> Get(ODataQueryOptions<BookInRequest> query)
{
var results = query.ApplyTo(_context.BookInRequests) as IQueryable<BookInRequest>;
var mappedResults = Mapper.Map<IQueryable<BookInRequest>, IQueryable<BookInRequestDto>>(results);
return mappedResults;
}
When I query: api/Get
, I get an appropriate response, but a Document's Properties
is set to null
response containing documents properties set to null.
When I query: api/Get?$expand=Documents/Properties
, the response is an empty array.
As I understand, this is because Select/Expand changes the shape of the response, so it no longer matches an IQueryable of BookInRequest, and instead returns an IQueryable.
I'm happy to return that, except I need to be able to apply the AutoMapper Mappings. Is there anything that can be done to enforce the shape of the query results?
I have the following entities:
public class BookInRequest {
//...
public virtual ICollection<BookInDocument> Documents { get; set; }
}
public class BookInDocument {
public ICollection<BookInDocumentProperty> Properties { get; set; }
}
With Corresponding DTO's that are pretty much identical, except for the BookInDocumentDto
:
public class BookInDocumentDto {
public dynamic Properties { get; set; }
}
My Mapping definition is as follows:
Mapper.CreateMap<BookInRequest, BookInRequestDto>();
Mapper.CreateMap<BookInDocument, BookInDocumentDto>()
.ForMember(x => x.Properties,
y => y.MapFrom(z =>
DynamicHelpers.PropertiesAsDynamic(z.Properties)));