【问题标题】:Automapper: mapping between different typesAutomapper:不同类型之间的映射
【发布时间】:2021-07-22 20:18:52
【问题描述】:

假设我有一个类似的类结构

public class Entity
{
    public List<EntityChild> Children { get; set; }
}

public class EntityChild
{
    public int Id { get; set; }
    public string Name { get; set; }
}

我想使用 AutoMapper 将 Entity 映射到类 EntityDto 并反转。

public class EntityDto
{
    public List<int> EntityChildrenIds { get; set; }
}

我不知道如何配置 AutoMapper 以在两个方向上正确映射。我知道从 EntityDto 映射到 Entity 时我的 Name 属性将为空,但这不会有问题。

【问题讨论】:

  • 反向地图要填名字吗?

标签: c# mapping automapper


【解决方案1】:

为了映射两种方式,此配置对我有用:

var mapperConfiguration = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Entity, EntityDto>()
      .ForMember(dest => dest.EntityChildrenIds, opt => opt.MapFrom(src => src.Children))
      .ReverseMap();

    cfg.CreateMap<EntityChild, int>().ConvertUsing(child => child.Id);
    cfg.CreateMap<int, EntityChild>().ConvertUsing(id => new EntityChild
    {
      Id = id
    });
});

由于属性具有不同的名称,我们需要配置该映射。

然后只需添加从EntityChildint 的通用映射,然后再返回,我们就完成了。

【讨论】:

    【解决方案2】:

    如果.ReverseMap(),正如@knoop 提到的那样,不起作用,也许你应该手动映射它:

    CreateMap<Entity, EntityDto>(MemberList.None)
        .ForMember(dest => dest.EntityChildrenIds, opts => opts.MapFrom(src => MapChildrenIds(src.Children)));
    
    
    CreateMap<EntityDto, Entity>(MemberList.None)
        .ForMember(dest => dest.Children, opts => opts.MapFrom(src => MapChildren(src.EntityChildrenIds)));
    
    
    private List<EntityChild> MapChildren(List<int> entityChildrenIds)
    {
        var listEntityChild = new List<EntityChild>();
    
        foreach (var childId in entityChildrenIds)
            listEntityChild.Add(new EntityChild { Id = childId });
    
        return listEntityChild;
    }
    private List<int> MapChildrenIds(List<EntityChild> children)
    {
        return children.Select(x => x.Id).ToList();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-23
      • 2017-07-08
      • 2016-08-11
      • 2018-11-15
      • 2012-12-25
      • 1970-01-01
      • 2017-12-23
      • 1970-01-01
      相关资源
      最近更新 更多