简体   繁体   English

Automapper 映射后不识别继承子类

[英]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:和我的 DTO:

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 中:

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

Any my DTO of this:我的任何 DTO:

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

And my automapper:还有我的自动映射器:

CreateMap<Shelter , ShelterDTO>();

So I fill this with data and map it:所以我用数据和 map 填充它:

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:这工作正常,现在我想 map 它:

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.虽然在我的“shell”中,Pet 是 Dog 并且具有 DogRace 属性,但映射的实例不是 Dog,它只是具有给定名称 Fiffy 但没有 DogRace 的 Pet。

What type of configuration did I miss?我错过了什么类型的配置?

You need to Include ( see here ) the derived classes in your mapping, for example:您需要在映射中Include参见此处)派生类,例如:

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

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

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

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

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