Setup Automapper in ASP.NET Core

时间:2024-11-16 17:34:19

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