【问题标题】:AutoMapper mapping the first item in an array and other propertiesAutoMapper 映射数组中的第一项和其他属性
【发布时间】:2018-05-04 21:37:06
【问题描述】:

我有一个对象:

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

【问题讨论】:

  • “似乎不起作用”是什么意思,你有什么错误?

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


【解决方案1】:

我不认为你可以使用 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);

【讨论】:

    猜你喜欢
    • 2019-04-12
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多