简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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