AutoMapper : Map both ways in Net Core 2 syntax

不羁的心 提交于 2019-12-07 10:38:27

I'd rather create a seprate 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(); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!