.Net Core 中使用AutoMapper


1、新建一個類

using AutoMapper;
using YourModels;
using YourViewModels;
namespace YourNamespace
{
    public class AutoMapperProfileConfiguration : Profile
    {
        protected override void Configure()
        {
            CreateMap<Application, ApplicationViewModel>();
            CreateMap<ApplicationViewModel, Application>();
            ...
        }
    }
}

 

2、在Startup.cs中增加MapperConfiguration屬性

private MapperConfiguration _mapperConfiguration { get; set; }

 

3、在Startup.cs中的Startup方法中增加

 

_mapperConfiguration = new MapperConfiguration(cfg =>
{
    cfg.AddProfile(new AutoMapperProfileConfiguration());
});

 

 

4、在ConfigureServices()中增加

services.AddSingleton<IMapper>(sp => _mapperConfiguration.CreateMapper());

 

5、使用

using AutoMapper;
using ...
namespace YourNamespace
{
    public class ApplicationsController : BaseController
    {
        [FromServices]
        private IMapper _mapper { get; set; }
        [FromServices]
        private IApplicationRepository _applicationRepository { get; set; }
        public ApplicationsController(
            IMapper mapper,
            IApplicationRepository applicationRepository)
        {
            _mapper = mapper;
            _applicationRepository = applicationRepository;
        }
        // GET: Applications
        public async Task<IActionResult> Index()
        {
            IEnumerable<Application> applications = await _applicationRepository.GetForIdAsync(...);
            if (applications == null)
                return HttpNotFound();
            List<ApplicationViewModel> viewModel = _mapper.Map<List<ApplicationViewModel>>(applications);
            return View(viewModel);
        }
        ...
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM