Setup Automapper in ASP.NET Core

得意犹堪夸世俗,诏黄新湿字如鸦。这篇文章主要讲述Setup Automapper in ASP.NET Core相关的知识,希望能为你提供帮助。
1、添加Nuget Package

Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection

2、修改Startup.cs
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddAutoMapper(); }

3、从Profile派生一个自定义的映射配置类
public class MappingProfile : Profile { public MappingProfile() { CreateMap< User, UserDTO> (); } }

【Setup Automapper in ASP.NET Core】4、在代码中调用映射对象
public class HomeController : Controller { private readonly IMapper _mapper; public HomeController(IMapper mapper) { _mapper = mapper; } public IActionResult Index() { var user = new User { Id = 1, Name = "bidianqing" }; var userDTO = _mapper.Map< User, UserDTO> (user); return View(); } }

 

    推荐阅读