How to use automapper to map a source class with nested members to a destination with no nested members

Viewed 284

Hi I recently found out that I can construct a request class so that in the controller parameters I don't need to have multiple [FromHeader] parameters and a [FromBody] parameter. Instead I created a class RequestForController below. As of right now to convert the request class to the entity class I need to create a map specifying all the members for destination and source. If the contracts/entities change then I would need to change it in the two classes as well as the automapper configuration. My goal is to configure automapper so that I do not need to maintain the automapper configuration when the contract/entity changes. I posted an example of my setup below

// Source class Body Members
public class RequestBody
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

// Source class Headers
public class RequestHeaders
{
    [FromHeader]
    public string SomeHeader { get; set; }
}

// Source Class
public class RequestForController
{
    public RequestHeaders Headers { get; set; }

    [FromBody, Required(ErrorMessage = "Request Body is missing")]
    public RequestBody Body { get; set; }
}

// Destination class
public class EntityModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string SomeHeader { get; set; }
}

// AutoMapper Configuration in Startup.cs
CreateMap<RequestForController, EntityModel>()
    .ForMember(dest => dest.FirstName, opt => opt.MapFrom(src => src.Body.FirstName))
    .ForMember(dest => dest.LastName, opt => opt.MapFrom(src => src.Body.LastName))
    .ForMember(dest => dest.SomeHeader, opt => opt.MapFrom(src => src.Headers.SomeHeader));

// Controller Function
public async Task<IActionResult> ApiEndpoint(RequestForController request)
{
    // do validation
    var entity = Mapper.Map<EntityModel>(request);
    // do work
    return Ok();
}
0 Answers
Related