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.
To test our configuration, we simply create a unit test that sets up the configuration and executes the AssertConfigurationIsValid method: var configuration = new MapperConfiguration(cfg => cfg. CreateMap<Source, Destination>()); configuration. AssertConfigurationIsValid();
AutoMapper is a simple library that helps us to transform one object type into another. It is a convention-based object-to-object mapper that requires very little configuration. The object-to-object mapping works by transforming an input object of one type into an output object of a different type.
AutoMapper is a popular object-to-object mapping library that can be used to map objects belonging to dissimilar types. As an example, you might need to map the DTOs (Data Transfer Objects) in your application to the model objects.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With