Gargoyle
Gargoyle

Reputation: 10375

Automapper ConstructUsing through a relationship

I have a mapping setup to go from my Entity Framework Software model to SoftwareDTO, which is working correctly when I project to it like this:

var stuff = await ChecklistLink.AsNoTracking()
    .Select(x => x.Software)
    .ProjectTo<SoftwareDTO>(config)
    .Distinct()
    .ToArrayAsync(cancellationToken);

I want to skip the select there and be able to directly project from ChecklistLink to the dto, so I added this map:

CreateMap<ChecklistLink, SoftwareDTO>()
    .ConstructUsing((entity, ctx) => ctx.Mapper.Map<SoftwareDTO>(entity.Software));

If I comment out the .Select(x => x.Software) line now, I get no results back. What do I need to do differently?

Upvotes: 1

Views: 71

Answers (1)

Guru Stron
Guru Stron

Reputation: 143098

One trick you can use is flattening:

cfg.CreateMap<ChecklistLink, SoftwareDTO>()
    .IncludeMembers(src => src.Software);

P.S.

If the mapping is needed only for queryable projections consider using CreateProjection instead of CreateMap (see this answer for a bit more details).

Upvotes: 2

Related Questions