simoneL
simoneL

Reputation: 622

Automapper: map a collection composed by base class objects

I am using 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.

I want to map Origin to Destination, so I have added this configuration:

 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. Instead I want that the B and C entities to be converted in B2 and C2 entities.

Any suggestion to achieve this?

Upvotes: 2

Views: 2312

Answers (1)

Yuliam Chandra
Yuliam Chandra

Reputation: 14640

You need to configure it too with Include.

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

More: Mapping Inheritance

Upvotes: 5

Related Questions