Home » C# » Automapper » Using AutoMapper to Map Abstract Classes

Using AutoMapper to Map Abstract Classes

AutoMapper lets you map from one class to another class your object. It works fine until you want to map from a class to an abstract class. The reason is that AutoMapper instantiates the desired class type and since an abstract class cannot be instantiate will crash.

Mapper.CreateMap<SelectorItem, OrderType>()
//Use the mapping
var model = AutoMapper.Mapper.Map<SelectorItem, OrderType>(viewModel);

The code create the map from SelectorItem that is a normal class and OrderType that is an abstract class. The use of this map will not work. To fix this problem the mapping configuration must be changed to specify to AutoMapper how to instantiate the OrderType class, the abstract class.

Mapper.CreateMap<SelectorItem, OrderType>()

The mapping requires the use of ConstructUsing method that has two signatures.

IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, TDestination> ctor);
IMappingExpression<TSource, TDestination> ConstructUsing(Func<ResolutionContext, TDestination> ctor);

The first one is easy to use. It takes a method that has the source which is the class we start with and return a destination class that is the abstract class.

private OrderType OrderTypeCreator(SelectorItem arg)
     return OrderType.GetFromId(arg.Id);

This example takes from the concrete class the ID and use a factory to return the correct concrete class that inherit form the abstract OrderType class.

This way, we have AutoMapper that can map to abstract Class without problem.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.