AutoMapper映射数组中的第一项和其他属性

时间:2017-11-21 12:10:32

标签: mapping asp.net-core-mvc automapper

我有一个对象:

public class TopLevel{
  public string AProperty {get;set;}
  public int AnotherProperty {get;set;}
  public SecondLevel[] SecondLevels {get;set;}
}

public class SecondLevel{
  public string AThing {get;set;}
  public int AnotherThing {get;set;}
}

我要映射到这个:

public class JoinedClass{
  public string AProperty {get;set;}
  public int AnotherProperty {get;set;}
  public string Athing {get;set;}
  public string AnotherThing {get;set;}
}

使用SecondLevels数组的FirstOrDefault成员。 我认为这是可能的,但似乎无法解决如何做到这一点。

我试过......

CreateMap<TopLevel, JoinedClass>()
  .ForAllMembers(opt=>opt.MapFrom(tl=>tl.SecondLevels.FirstOrDefault())
  .ForMemeber(jc=>jc.AProperty, opt=>opt.MapFrom(tl=>tl.AProperty)
  .ForMemeber(jc=>jc.AnotherProperty , opt=>opt.MapFrom(tl=>tl.AnotherProperty );

但似乎根本没有映射任何属性。我还将ForAllMembers()放在上面的映射中,也没有运气。 我正在使用AutoMapper 6.2.0

1 个答案:

答案 0 :(得分:0)

我不认为你可以使用 ForAllMembers 你总是可以一对一地映射,这是一个例子

设置映射配置

public static MapperConfiguration SetupMapping()
{
    return new MapperConfiguration(cfg =>
    {
        cfg.CreateMissingTypeMaps = true;
        cfg.CreateMap<TopLevel, JoinedClass>()
            .ForMember(jc => jc.Athing, opt => opt.MapFrom(t1 => t1.SecondLevels.FirstOrDefault().AThing))
            .ForMember(jc => jc.AnotherThing, opt => opt.MapFrom(t1 => t1.SecondLevels.FirstOrDefault().AnotherThing))
            ;
    });
}

示例

var seconds = new SecondLevel[] {
new SecondLevel { AThing = "one", AnotherThing = 1 },
new SecondLevel { AThing = "two", AnotherThing = 2 }
        };

var toplevel = new TopLevel { AProperty = "top", AnotherProperty = 99, SecondLevels = seconds };

MapperConfiguration config = SetupMapping();
IMapper mapper = config.CreateMapper();

var result = mapper.Map<JoinedClass>(toplevel);