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

  1. 安装nuget包Asp .net core中使用AutoMapper数据映射

  2. 注册服务

    services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
    
  3. 创建映射配置文件Asp .net core中使用AutoMapper数据映射

  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映射Asp .net core中使用AutoMapper数据映射

上一篇:使用C#写MVC框架(一:核心原理) HttpHandler


下一篇:如何在 .NetCore 中使用 AutoMapper 高级功能