无法映射其中一个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:
如何正确配置TicketViewModel的映射?
感谢#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从第一个映射中自动获取,因此它们是不必要的。