Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper with base class and different configuration options for implementations

Tags:

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.

like image 578
Hrvoje Hudo Avatar asked Jun 29 '12 15:06

Hrvoje Hudo


People also ask

How do I test AutoMapper configuration?

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();

What is AutoMapper good for?

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.

What is an AutoMapper?

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.


1 Answers

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) 
like image 130
k0stya Avatar answered Oct 14 '22 09:10

k0stya