Start by installing the AutoMapper extension from the package manager in your project. In PowerShell, or with the package manager console in Visual Studio, type:

Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection

Register a service in ConfigureServices in the startup.cs file:

// startup.cs

using AutoMapper; 
public void ConfigureServices(IServiceCollection services)
{ 
    services.AddAutoMapper(typeof(Startup)); 
}

Add an AutoMapping.cs file with the following content:

// AutoMapping.cs

public class AutoMapping : Profile
{
    public AutoMapping()
    {
        CreateMap<CreateProductRequest, Product>();
    }
}

Inject a mapper into your controller:

private readonly IMapper mapper;
public ProductController(IMapper mapper)
{
    this.mapper = mapper;
}

Now you can do the mapping like this in your code:

public async Task<ActionResult> CreateProduct(CreateProductRequest request)
{
    var product = mapper.Map<Product>(request);
...

Voila! Now, whenever you add new properties to your object the mapping should be handled automatically.

Last modified: December 9, 2020

Author

Comments

Write a Reply or Comment

Your email address will not be published.