Setup Automapper in ASP.NET Core

Posted bidianqing

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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>();
    }
}

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();
    }
}

 

以上是关于Setup Automapper in ASP.NET Core的主要内容,如果未能解决你的问题,请参考以下文章

3AutoMapper In Asp.net Core

如何在 C# 中使用 AutoMapper

Python setup.py和MANIFEST.in文件

Setup and Configure the vsftpd server in CentOS 7 operation system

How to setup Assigned Access in Windows 10 (Kiosk Mode) 设置分配的访问权限(Kiosk模式)

location of the android sdk has not been setup in the preferences