AutoMapper ProjectTo()配置问题

问题描述 投票:0回答:1

无法映射其中一个Dto:

视图模型:

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的映射?

c# asp.net-core entity-framework-core automapper
1个回答
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从第一个映射中自动获取,因此它们是不必要的。

© www.soinside.com 2019 - 2024. All rights reserved.