简体   繁体   English

自动映射:映射由基类对象组成的集合

[英]Automapper: map a collection composed by base class objects

I am using AutoMapper . 我正在使用AutoMapper

I have some problem mapping collections. 我有一些问题映射集合。 This is the simplified structure. 这是简化的结构。

public class A
{
}

public class B : A
{ 
}

public class C : A
{ 
}

public class Origin
{
    public List<A> Entities {get; set;}
}

 /********************/

public class A2
{
}

public class B2 : A2
{ 
}

public class C2 : A2
{ 
}

public class Destination
{
    public List<A2> Entities {get; set;}
}

The Origin class has a collection of A objects, filled with A, B or C instances. Origin类有一个A对象的集合,用A,B或C实例填充。

I want to map Origin to Destination, so I have added this configuration: 我想将Origin映射到Destination,所以我添加了这个配置:

 Mapper.CreateMap<C, C2>();
 Mapper.CreateMap<B, B2>();
 Mapper.CreateMap<A, A2>();

The problem is that when the Entities collection in Origin is mapped to the collection in Destination, all the objects are mapped only to A2 entites. 问题是当Origin中的Entities集合映射到Destination中的集合时,所有对象仅映射到A2 entites。 Instead I want that the B and C entities to be converted in B2 and C2 entities. 相反,我希望B和C实体在B2和C2实体中转换。

Any suggestion to achieve this? 有任何建议来实现这一目标吗?

You need to configure it too with Include . 您还需要使用Include进行配置。

Mapper.CreateMap<C, C2>();
Mapper.CreateMap<B, B2>();
Mapper.CreateMap<A, A2>().Include<B, B2>().Include<C, C2>();

More: Mapping Inheritance 更多: 映射继承

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM