26

I have two classes (MVC view model) which inherits from one abstract base class.

abstract class BaseModel { }

class Car : BaseModel 
{
    public string Speed { get; set; }
}

class Camper : BaseModel
{
    public int Beds { get; set; } 
}

and want to configure AutoMapper with base class, something like:

Mapper.CreateMap<BaseModel, DataDestination>();

var someObj = new DataDastination();
Mapper.Map(instanceOfBaseModel, someObj);

Here I get error, because Automapper doesn't have configuration of Car or Camper. Tried configuring Automapper with something like this:

Mapper.CreateMap<BaseModel, DataDestination>()
    .ForMember(dest => dest.SomeProp, mapper => mapper.MapFrom( .... ));

In MapFrom, I only see properties from base class! How to configure Automapper to use BaseClass, and specific ForMember expression for Car and Camper? For example, if it's a Car, map this property from this, and if it's a Camper, map this property from somewhere else.

Hrvoje Hudo
  • 8,994
  • 5
  • 33
  • 42

2 Answers2

41

Here is the topic describing Mapping Inheritance.

The following should work for you:

Mapper.CreateMap<BaseModel, DataDastination>()
    .Include<Car, DataDastination>()
    .Include<Camper, DataDastination>();//.ForMember(general mapping)
Mapper.CreateMap<Car, DataDastination>();//.ForMember(some specific mapping)
Mapper.CreateMap<Camper, DataDastination>();//.ForMember(some specific mapping)
Richard Ev
  • 52,939
  • 59
  • 191
  • 278
k0stya
  • 4,267
  • 32
  • 41
  • 1
    Not worked for a similar situation explained on [Cannot map from ViewModel to ApplicationUser in AutoMapper 5](http://stackoverflow.com/questions/39541588/cannot-map-from-viewmodel-to-applicationuser-in-automapper-5?noredirect=1#comment66397101_39541588). Any idea? – Jack Sep 17 '16 at 00:38
  • You saved my day:) – Kalyan Nov 27 '18 at 22:14
  • Shamefully, I don't always reference docs in the first instance. This is a perfect example as to why I should. Thank you. – ColinM Nov 13 '20 at 18:13
9

Use .IncludeAllDerived()

Mapper.CreateMap<BaseModel, DataDestination>().IncludeAllDerived()
Mapper.CreateMap<Car, DataDestination>();
Mapper.CreateMap<Camper, DataDestination>();
jimebe
  • 93
  • 1
  • 4