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
{
     
    /// 
    /// 配置构造函数,用来创建关系映射
    /// 
    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());
    }
}

你可能感兴趣的:(C#,c#)