AutoMapper ProjectTo() configuration question

落爺英雄遲暮 提交于 2019-12-13 04:29:57

问题


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.



来源:https://stackoverflow.com/questions/52164963/automapper-projectto-configuration-question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!