• .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);
            }
            ...
    }
  • 相关阅读:
    nopcommerce商城系统--文档整理
    浏览器标签页显示图标
    SQL SERVER 查询语句学习:CHARINDEX
    NHibernate3.3.3 学习笔记1
    权限管理UML设计草图
    jquery UI 跟随学习笔记——拖拽(Draggable)
    Unity3d IOS中的IGUI控件
    Unity3d ngui基础教程
    unity3d 幻灯片效果实现
    unity3d 场景间数据传递
  • 原文地址:https://www.cnblogs.com/ideacore/p/6282994.html
Copyright © 2020-2023  润新知