ASP.NET CORE 3.1 WebApiはAutoMapperを参照

11621 ワード

一、参照パッケージの追加
  <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

四、使用、サーヴァント層で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());
    }
}