Using Automapper in each of my layers to do the boring mapping. However, one thing I haven't solved is how to use AutoMapper to map from DTOs in the Application Layer from my QueryResults to ViewModels.

For example, let's say I need my ViewModel to format the state from a Customer's address by shortening it to its 2-letter abbreviation (e.g. "South Carolina" to "SC").

It appears that Automapper just does a 1:1 mapping, but I obviously need to invoke formatting logic.

public class IndexModel : PageModel
{
    public List<ProductViewModel> ProductViews { get; private set; }

    public IndexModel(IMediator mediator)
    {
        _mediator = mediator;
    }

    public async Task OnGetAsync()
    {
        var productResult = await _mediator.Send(new TopSellingProductsQuery
        {
            NumberOfProducts = 12
        });

        // Here is where I'm wondering how logic can be added to my view models
        ProductViews = Mapper.Map<List<ProductDTO>, List<ProductViewModel>>(productResult.Products);
    }

    private readonly IMediator _mediator;
}

closed as off-topic by Greg Burghardt, Doc Brown, David Arno, BobDalgleish, Jörg W Mittag Dec 8 at 12:13

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions asking for assistance in explaining, writing or debugging code are off-topic here. These can be asked on Stack Overflow if they include the desired behavior, a specific problem or error, and the shortest code necessary to reproduce it in the question (see Minimal, Complete, and Verifiable Example)." – Greg Burghardt, BobDalgleish, Jörg W Mittag
If this question can be reworded to fit the rules in the help center, please edit the question.

Automapper not map only 1:1 mapping. Mapping depend to your mapping config profile.

You may use ForMember method with MapFrom or ResolveUsing for how automapper map your properties.

I am using for example

CreateMap<CHNGCUS.ChangeCustomerRequestModel, GCON.CustomerDto>()
    .ForMember(dest => dest.Address, opts => opts.MapFrom(src => src.DeliveryAddress))
    .ForMember(dest => dest.AcademicDegree,
        opts => opts.ResolveUsing(src =>
            string.IsNullOrEmpty(src.AcademicDegree)
                ? AcademicDegreeEnum.None
                : Enum.Parse<AcademicDegreeEnum>(src.AcademicDegree)));

FYInspiration

Not the answer you're looking for? Browse other questions tagged or ask your own question.