Search code examples
c#entity-framework-coreautomapperef-core-8.0automapper-13

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?


Solution

  • 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).