简体   繁体   English

使用AutoMapper将IEnumerable映射到具有一个列表作为属性的类

[英]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.

相关问题 映射列表的属性 <T> 使用自动映射器 - Mapping A Property Of List<T> Using Automapper 忽略使用 Automapper 映射一个属性 - Ignore mapping one property with Automapper 使用自动映射器将字符串类型的列表映射到具有字符串属性的对象列表 - Mapping a list of type string to a list of objects with a string property using automapper 防止Automapper将IEnumerable属性转换为列表 - Prevent Automapper converting IEnumerable Property to List AutoMapper IEnumerable映射错误 - AutoMapper IEnumerable mapping bug AutoMapper 未映射 IEnumerable 问题 - AutoMapper not mapping IEnumerable Issues IEnumerable到EntityCollection使用嵌套映射与自动映射器进行映射失败 - IEnumerable to EntityCollection failed mapping with automapper using nested mapping 如何 map IEnumerable<model> 到带有 IEnumerable 的 DTO<anotherdto> 使用自动映射器的属性?</anotherdto></model> - How to map IEnumerable<Model> to a DTO with IEnumerable<AnotherDto> property using automapper? 使用“ AutoMapper”将其中具有类列表的类映射到具有类似属性的另一个类中 - Map a class with List of class in it into another class of similar property using “AutoMapper” 将通用IEnumerable映射到通用列表时,自动映射器失败 - Automapper failing while mapping generic IEnumerable to generic List
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM