编程语言
首页 > 编程语言> > Asp .net core中使用AutoMapper数据映射

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

标签:opt,core,MapFrom,Asp,src,dest,ForMember,CreateMap,AutoMapper
来源: https://www.cnblogs.com/bleso/p/15187486.html