John Mills
John Mills

Reputation: 10263

How do I map an inheritance hierarchy with Automapper?

I have the following example classes being used in an MVC/MVVM type app:

class A
{
   public string Property1 { get; set; }
}

class B : A
{
   public string Property2 { get; set; }
}

class ViewModel
{
   public string Property1 { get; set; }
   public string Property2 { get; set; }
}

A is my base class and B is the derived class. ViewModel is meant to encompass both A & B.

I want to use AutoMapper to map from both A & B to ViewModel. What is the best way to do this?

Assuming I have complex properties on A that require a .ForMember call, do I then have to repeat the same mappings for those complex properties when creating the map from B to ViewModel or is there a way to inherit/reuse the map from A to ViewModel?

Upvotes: 1

Views: 821

Answers (1)

Jimmy Bogard
Jimmy Bogard

Reputation: 26765

If you map A to ViewModel, you will need to Ignore() members that don't exist on A, and repeat any configuration that needs to be shared.

Inheritance is just a tough nut, where behavior starts to become complex and less conventional. You can, however, create an extension method on the configuration API to encapsulate all of the duplicate configuration calls.

Upvotes: 1

Related Questions