zoukankan      html  css  js  c++  java
  • .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);
            }
            ...
    }
  • 相关阅读:
    面试题33:把数组排成最小的数
    面试题32:从1到n整数中1出现的次数
    面试题31:连续子数组的最大和
    HTTPS 及加密信息全解析
    面试题30:最小的k个数
    linux退出vi
    linux清除当前屏幕
    java web开发环境配置
    jQuery积累
    html5离线应用详摘
  • 原文地址:https://www.cnblogs.com/ideacore/p/6282994.html
Copyright © 2011-2022 走看看