PassionateDeveloper
PassionateDeveloper

Reputation: 15138

Automapper does not recognize inheritence sub classes after mapping

I have:

class Pet { string name {get;set;} }
class Dog : Pet { string dograce {get;set;} }
class Cat : Pet { string catrace {get;set;} }

and my DTOs:

class PetDTO { string name {get;set;} }
class DogDTO : PetDTO{ string dograce {get;set;} }
class CatDTO : PetDTO { string catrace {get;set;} }

Now my automapper setup is quiet simple for these:

CreateMap<Pet, PetDTO>();
CreateMap<Dog, DogDTO>();
CreateMap<Cat, CatDTO>();

So now I add these pets into my shelter class:

class Shelter { List<Pet> MyPets {get;set;} }

Any my DTO of this:

class ShelterDTO { List<PetDTO> MyPets {get;set;} }

And my automapper:

CreateMap<Shelter , ShelterDTO>();

So I fill this with data and map it:

Shelter shel = new Shelter();
shel.MyPets = new List<Pet>();
shel.MyPets.Add(new Dog() { Name = "Fiffy", DogRace = "NiceDog" };

This works fine, now I want to map it:

var data = mapper.map<ShelpterDTO>(shel);

And here is the point. While in my "shel" the Pet is a Dog and has the property DogRace, the mapped instance is not a Dog, its only a Pet with the given Name Fiffy but without the DogRace.

What type of configuration did I miss?

Upvotes: 1

Views: 305

Answers (1)

DavidG
DavidG

Reputation: 118937

You need to Include (see here) the derived classes in your mapping, for example:

CreateMap<Dog, DogDTO>();
CreateMap<Cat, CatDTO>();

CreateMap<Pet, PetDTO>()
    .Include<Dog, DogDTO>()
    .Include<Cat, CatDTO>();

Example: https://dotnetfiddle.net/8geXDV

Upvotes: 3

Related Questions