在.net core中使用AutoMapper

1、新建一个类
   
   
  1. using AutoMapper;
  2. using YourModels;
  3. using YourViewModels;
  4. namespace YourNamespace
  5. {
  6. public class AutoMapperProfileConfiguration : Profile
  7. {
  8. protected override void Configure()
  9. {
  10. CreateMap<Application, ApplicationViewModel>();
  11. CreateMap<ApplicationViewModel, Application>();
  12. ...
  13. }
  14. }
  15. }
2、在Startup.cs中增加 MapperConfiguration 属性
   
   
  1. private MapperConfiguration _mapperConfiguration { get; set; }
3、在Startup.cs中的 Startup方法中增加
    
    
  1. _mapperConfiguration = new MapperConfiguration(cfg =>
  2. {
  3. cfg.AddProfile(new AutoMapperProfileConfiguration());
  4. });
4、在 ConfigureServices()中增加
    
    
  1. services.AddSingleton<IMapper>(sp => _mapperConfiguration.CreateMapper());
5、使用
    
    
  1. using AutoMapper;
  2. using ...
  3. namespace YourNamespace
  4. {
  5. public class ApplicationsController : BaseController
  6. {
  7. [FromServices]
  8. private IMapper _mapper { get; set; }
  9. [FromServices]
  10. private IApplicationRepository _applicationRepository { get; set; }
  11. public ApplicationsController(
  12. IMapper mapper,
  13. IApplicationRepository applicationRepository)
  14. {
  15. _mapper = mapper;
  16. _applicationRepository = applicationRepository;
  17. }
  18. // GET: Applications
  19. public async Task<IActionResult> Index()
  20. {
  21. IEnumerable<Application> applications = await _applicationRepository.GetForIdAsync(...);
  22. if (applications == null)
  23. return HttpNotFound();
  24. List<ApplicationViewModel> viewModel = _mapper.Map<List<ApplicationViewModel>>(applications);
  25. return View(viewModel);
  26. }
  27. ...
  28. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值