Search code examples
.net-coreautomapper.net-core-2.0

AutoMapper : Map both ways in Net Core 2 syntax


What is syntax to map both ways in AutoMapper Net Core2? I need to map ProductViewModel and ProductDto both ways. This is not working,

Startup.cs

var config = new MapperConfiguration
(
    cfg => cfg.CreateMap<Models.ProductDto, Models.ProductViewModel>(),
    cfg => cfg.CreateMap<Models.ProductViewModel, Models.ProductDto>()
);

var mapper = config.CreateMapper();

Solution

  • I'd rather create a separate initializer and mapper. e.g here is my AutoMapperStartupTask class.

    public static class AutoMapperStartupTask
    {
        public static void Execute()
        {
            Mapper.Initialize(
                cfg =>
                {
                    cfg.CreateMap<ProductViewModel, ProductDto>()
                        .ReverseMap();
                });
        }
    }
    

    And Mapper

    public static class DtoMapping
    {
        public static ProductViewModel ToModel(this ProductDto dto)
        {
            return Mapper.Map<ProductDto, ProductViewModel>(dto);
        }
    
        public static ProductDto ToDto(this ProductViewModel dto)
        {
            return Mapper.Map<ProductViewModel, ProductDto>(dto);
        }
    }
    

    Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
       AutoMapperStartupTask.Execute();
    }
    

    Use in Controller

    var dto = productModel.ToDto();
    var model = productDto.ToModel();