AutoMapper ProjectTo()配置问题

时间:2018-09-04 11:09:53

标签: c# asp.net-core entity-framework-core automapper

无法映射Dto之一:

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和TicketState是导航属性。

查询:

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>();

映射:

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)
        );

查询中填充的票证数据,但未投影到TicketDto:

enter image description here

如何正确配置TicketViewModel的映射?

1 个答案:

答案 0 :(得分:1)

感谢#5984640,我知道了:

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
        );

Automapper的注释行是从第一个映射自动获取的,因此它们是不必要的。