ASP.NET CORE 3.1 WebApi 引用AutoMapper

一、添加引用包

  <PackageReference Include="AutoMapper" Version="10.1.1" />
  <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.1.1" />

二、创建实体和视图实体

public class DemoViewModel
{
    public string DemoName { get; set; }
}
public class Demo
{
    public int Id { get; set; }
    public string Name { get; set; }
}

三、映射关系配置

public class CustomProfile:Profile
{
    /// <summary>
    /// 配置构造函数,用来创建关系映射
    /// </summary>
    public CustomProfile()
    {
        CreateMap<Demo, DemoViewModel>().ForMember(d=>d.DemoName,o=>o.MapFrom(s=>s.Name));
        CreateMap<DemoViewModel, Demo>().ForMember(d=>d.Name,o=>o.MapFrom(s=>s.DemoName));
    }
}
public static class AutoMapperSetup
{
     public static void AddAutoMapperSetup(this IServiceCollection services)
     {
         if (services == null) throw new ArgumentNullException(nameof(services));

         services.AddAutoMapper(typeof(AutoMapperConfig));
         AutoMapperConfig.RegisterMappings();
     }
 }
public class AutoMapperConfig
{
     public static MapperConfiguration RegisterMappings()
     {
         return new MapperConfiguration(cfg =>
         {
             cfg.AddProfile(new CustomProfile());
         });
     }
 }
 #region AutoMapper
 services.AddAutoMapperSetup();
 #endregion

四、使用,在Serv层调用IMapper

public class DemoServ : IDemoServ
{
    private readonly IDemoRepo _demoRepo;
    private readonly IMapper _mapper;

    public DemoServ(IDemoRepo demoRepo,IMapper mapper)
    {
        _demoRepo = demoRepo;
        _mapper = mapper;
    }

    public DemoViewModel GetDemos()
    {
        return _mapper.Map<DemoViewModel>(_demoRepo.GetDemos());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值