[英]Mapping IEnumerable to class with one list as a property - using AutoMapper
I am receiving an IEnumerable<Class1> from a third party api. 我从第三方api接收到IEnumerable <Class1>。
I would like to map it using Automapper to the following class: 我想使用Automapper将其映射到以下类:
public class WrapperClass
{
public List<Class2> Items { get; set; }
}
So essentially I am thinking I need two mappings: 所以本质上我在想我需要两个映射:
IEnumerable<Class1> ----> WrapperClass
_______
Class1 ----> Class2
How would I approach this in Automapper ? 我将如何在Automapper中进行处理 ?
Yes, you must first create mappings for map Class1 to Class2 like: 是的,您必须首先为映射Class1到Class2创建映射,如下所示:
AutoMapper.Mapper.CreateMap<Class1, Class2>().ForMember(x => x.A, y => y.MapFrom(z => z.B));
Then create mapping for map collection on class like: 然后在类上为地图集合创建映射:
AutoMapper.Mapper.CreateMap<IEnumerable<Class1>, WrapperClass>().ForMember(x => x.Items, y => y.MapFrom(z => z));
Finally you can use it like: 最后,您可以像这样使用它:
var wrapperClass = AutoMapper.Mapper.Map<IEnumerable<Class1>, WrapperClass>(/* list */);
Below three class used for this example: 下面的三个类用于此示例:
public class WrapperClass
{
public List<Class2> Items { get; set; }
}
public class Class2 {
public int A { get; set; }
}
public class Class1
{
public int B { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.