AutoMapper .net6

1.程序集下包 安装AutoMapper

2.创建一个类 继承Profile

public class AutoMapperProfile:Profile
{
    //构造函数
    public AutoMapperProfile()
    {
        //CreateMap<源对象,目标对象>  ReverseMap反转映射
        CreateMap<UserInfo, AddUserDto>().ReverseMap();

        //两个对象中属性名不同时,使用ForMember进行映射
        CreateMap<UserInfo, AddUserDto>().ReverseMap().ForMember(x => x.UserName, opt => opt.MapFrom(x => x.UserName11111));

    }
}

3.在Program中将AutoMapper注入到服务中

builder.Services.AddAutoMapper(typeof(AutoMapperProfile));

4.将IMapper注入到使用的位置

 private readonly IMapper _iMapper;

 public UserService(IMapper iMapper)
 {
     _iMapper = iMapper;
 }

5._mapper.Map<目标对象>(源对象值);!!!!!!!!!!!!!!!!!!!
var userInfo = _iMapper.Map<UserInfo>(data);

官网地址:https://docs.automapper.org/en/stable/

posted @ 2024-06-25 16:12  Twolp  阅读(10)  评论(0编辑  收藏  举报