安装nuget包
注册服务
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
创建映射配置文件
配置类如下
public class TouristRouteProfile : Profile { public TouristRouteProfile() { CreateMap<TouristRoute, TouristRouteDto>() .ForMember( dest => dest.Price, opt => opt.MapFrom(src => src.OriginalPrice * (decimal) (src.DiscountPresent ?? 1))) .ForMember( dest => dest.TravelDays, opt => opt.MapFrom(src => src.TravelDays)) .ForMember( dest => dest.TripType, opt => opt.MapFrom(src => src.TripType)) .ForMember( dest => dest.DepartureCity, opt => opt.MapFrom(src => src.DepartureCity)); CreateMap<TouristRouteForCreationDto, TouristRoute>() .ForMember( dest => dest.Id, opt => opt.MapFrom(src => Guid.NewGuid())); CreateMap<TouristRouteForUpdateDto, TouristRoute>(); CreateMap<TouristRoute, TouristRouteForUpdateDto>(); } }
注入依赖
private readonly IMapper _mapper;
使用mapper映射