AutoMapper:以Net Core 2语法双向映射 [英] AutoMapper : Map both ways in Net Core 2 syntax

查看:141
本文介绍了AutoMapper:以Net Core 2语法双向映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在AutoMapper Net Core2中双向映射的语法是什么?
我需要同时映射 ProductViewModel ProductDto

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

Startup.cs

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

var mapper = config.CreateMapper();


推荐答案

我宁愿创建一个单独的初始化器和映射器。例如,这是我的 AutoMapperStartupTask 类。

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();
            });
    }
}

和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

Startup.cs

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

在控制器中使用

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

这篇关于AutoMapper:以Net Core 2语法双向映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆