使用AutoMap将数据模型转换为DTO视图模型

2021-06-27  本文已影响0人  浅谈码生活

引言:在日常的开发过程中,根据业务需求,通常前端需要的数据往往不是“数据模型”的全部信息,因此我们将“数据模型”转换成我们所需要的“视图模型数据”。

常规做法:

//数据模型
var touristRouteFromRepo = _touristRouteRepository.GetTouristRoute(touristRouteId);
//DTO模型
var touristRouteDto = new TouristRouteDto()
 {
                Id = touristRouteFromRepo.Id,
                Title = touristRouteFromRepo.Title,
                Description = touristRouteFromRepo.Description,
                Price = touristRouteFromRepo.OriginalPrice * (decimal)(touristRouteFromRepo.DiscountPresent ?? 1),
                CreateTime = touristRouteFromRepo.CreateTime,
                UpdateTime = touristRouteFromRepo.UpdateTime,
                Features = touristRouteFromRepo.Features,
                Fees = touristRouteFromRepo.Fees,
                Notes = touristRouteFromRepo.Notes,
                Rating = touristRouteFromRepo.Rating,
                TravelDays = touristRouteFromRepo.TravelDays.ToString(),
                TripType = touristRouteFromRepo.TripType.ToString(),
                DepartureCity = touristRouteFromRepo.DepartureCity.ToString()
  };

使用AutoMap:
1.)使用NuGet引入AutoMap框架;
2.)创建“Profile”映射文件并建立映射关系;

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.ToString())
            )
            .ForMember(
                dest => dest.TripType,
                opt => opt.MapFrom(src => src.TripType.ToString())
            )
            .ForMember(
                dest => dest.DepartureCity,
                opt => opt.MapFrom(src => src.DepartureCity.ToString())
            );
    }
}

3.使用AutoMap生成DTO类:

 var touristRouteDto = _mapper.Map<TouristRouteDto>(touristRouteFromRepo);

总结:在创建AutoMap时,AutoMap会扫描当前程序集中所有“ProFile”文件,并根据文件中构造方法配置映射条件;

上一篇下一篇

猜你喜欢

热点阅读