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