Asp .net core中使用AutoMapper数据映射

  1. 安装nuget包image-20210825230258198

  2. 注册服务

    services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
    
  3. 创建映射配置文件image-20210825230610504

  4. 配置类如下

    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>();
            }
        }
    
  5. 注入依赖

    private readonly IMapper _mapper;
    
  6. 使用mapper映射image-20210825231351726

posted @ 2021-08-25 23:21  bleso  阅读(11)  评论(0编辑  收藏  举报