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

2021/8/26 1:06:12

本文主要是介绍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



这篇关于Asp .net core中使用AutoMapper数据映射的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程