C# – Automapper with base class and different configuration options for implementations

automappercnet

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.

Best Answer

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)
Related Topic