lwl1569  

Dto用于封装传输模型,完成从业务Model到前端数据模型Dto的转换,Profile用于封装Model到Dto的映射方法
例:

//原始Model,包含映射关系等内容
public class TouristRoutePicture
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { set; get; }
    [MaxLength(100)]
    public string Url { set; get; }
    [ForeignKey("TouristRouteId")]
    public Guid TouristRouteId { set; get; }
    public TouristRoute TouristRoute { set; get; }
}
//Dto,用于传递API参数
public class TouristRoutePictureDto
{
    public int Id { set; get; }
    public string Url { set; get; }
    public Guid TouristRouteId { set; get; }
}

最简单的Dto封装方法,在Controller返回数据前进行数据封装映射:

public class TouristRoutePicturesController : ControllerBase
{
    [HttpGet("{pictureId}")]
    public IActionResult GetPicture(Guid touristRouteId, int pictureId)
    {
        TouristRoutePicture pictureFromRepo = _touristRouteRepository.GetPicture(pictureId);
            TouristRoutePictureDto touristRoutePictureDto = new TouristRoutePictureDto()//此处对Dto和Model之间进行数据映射
            {
                Id = pictureFromRepo.Id,
                TouristRouteId = pictureFromRepo.TouristRouteId,
                Url = pictureFromRepo.Url
            };
            return Ok(touristRoutePictureDto);
    }
}

或者使用Mapper插件进行映射:(依赖项:AutoMapper.Extensions.Microsoft.DependencyInjection)

//映射代码:
using AutoMapper;
public class TouristRoutePictureProfile:Profile
{
    public TouristRoutePictureProfile()
    {
        CreateMap<TouristRoutePicture, TouristRoutePictureDto>();//若Dto内的属性均可在Model内找到,Mapper会自动配置其映射关系
                .ForMember(//对于Dto内不能在Model内找到的属性,需要用ForMember进行自定义配置
                dest => dest.TravelDays,//第一个表达式内属性为Dto内属性,例如TravelDays
                opt => opt.MapFrom(src => src.OriginalPrice * (decimal)(src.DiscountPresent ?? 1))//第二个表达式内属性为Model内属性,可以做运算
                )
                .ForMember(//ForMember可以多次使用,用于自定义配置
                dest => dest.TravelDays,
                opt => opt.MapFrom(src => src.TravelDays.ToString())
                )
//在调用时若_mapper.Map<TouristRoutePicture>(TouristRoutePictureDto),则配置的映射为CreateMap<TouristRoutePictureDto, TouristRoutePicture>();
    }
}
//在controller中的调用代码
public class TouristRoutePicturesController : ControllerBase
{
    [HttpGet("{pictureId}")]
    public IActionResult GetPicture(Guid touristRouteId, int pictureId)
    {
        TouristRoutePicture pictureFromRepo = _touristRouteRepository.GetPicture(pictureId);
        TouristRoutePictureDto touristRoutePictureDto =_mapper.Map<TouristRoutePictureDto>(pictureFromRepo);//此处对Dto和Model之间进行数据映射
        return Ok(touristRoutePictureDto);
    }
}

更多想关内容查看https://blog.csdn.net/catshitone/article/details/109840926

posted on 2021-09-08 11:18  lwl1569  阅读(209)  评论(0编辑  收藏  举报