AutoMapper ProjectTo() configuration question

2019-08-21 08:28发布

问题:

Not able to map one of the Dto's:

ViewModel:

public class TicketViewModel
{
    public TicketDto Ticket { get; set; }

    public CompanyDto Company { get; set; }

    public TicketStateDto TicketState { get; set; }

    public string TicketPriorityName { get; set; }
}

Company and TicketState are navigation properties.

Query:

var query = _ticketRepository.GetAll() // return IQueryable<Ticket>
             .Include(c=> c.Company)
             .Include(tt => tt.TicketState)
             .Include(ts => ts.TicketPriority)
             .OrderBy(n => n.Id)
        .ProjectTo<TicketViewModel>();

Mappings:

configuration.CreateMap<Ticket, TicketDto>();
configuration.CreateMap<TicketState, TicketStateDto >();
configuration.CreateMap<Company, CompanyDto >();

configuration.CreateMap<Ticket, TicketViewModel>()
            .ForMember(dest => dest.Company, conf => conf.MapFrom(src => src.Company ))
            .ForMember(dest => dest.TicketState, conf => conf.MapFrom(src => src.TicketState))
            .ForMember(dest => dest.TicketPriorityName, conf => conf.MapFrom(src => src.TicketPriority.Name)
        );

Ticket data populated in query, but not projected to TicketDto:

How to correctly configure mapping for TicketViewModel?

回答1:

Thanks to #5984640, i figured it out:

configuration.CreateMap<Ticket, TicketDto>();
configuration.CreateMap<TicketState, TicketStateDto >();
configuration.CreateMap<Company, CompanyDto >();

configuration.CreateMap<Ticket, TicketViewModel>()
            // .ForMember(dest => dest.Company, conf => conf.MapFrom(src => src.Company ))
            // .ForMember(dest => dest.TicketState, conf => conf.MapFrom(src => src.TicketState))
            // .ForMember(dest => dest.TicketPriorityName, conf => conf.MapFrom(src => src.TicketPriority.Name)
            .ForMember(dest => dest.Ticket, conf => conf.MapFrom(src => src) // <= required configuration
        );

The commented lines Automapper got automatically from the first mappings, so they are unnecessary.