1

I have base class

 public abstract class DtoBase //NOTICE that this class is abstract
 {
     //some DTO specific things
 }

 public class concreteA_Dto : DtoBase
 {
     //some properties from A
 }

 public class concreteB_Dto : DtoBase
 {
     //some properties from B
 }

and then i have some classes and they dont know each other and

 public class concreteA //NOTICE that there is NO base class
 {
     //some properties from A
 }

 public class concreteB
 {
     //some properties from B
 }

What i want is to Use Automapper this way:

 private DtoBase GetResourceDto(object value)
 {
    return Mapper.Map<DtoBase>(value);
 }  

So far my mapping looks like this:

CreateMap<concreteA, DtoBase>()
    .Include<concreteA, concreteA_Dto>();

CreateMap<concreteA, concreteA_Dto>();

But when i call method GetResourceDto with some instance of concreteA i will get

Automapper exception:

Mapping types:
concreteA-> DtoBase
#NAMESPACE.concreteA -> #NAMESPACE.DtoBase

Destination path:
DtoBase

with inner exception

Instances of abstract classes cannot be created.

Note that #NAMESPACE is my namespace of class

How to perform proper mapping that will avoid this exception ?

Idea behind this is that concreteA and concreteB can dynamicaly grow in time and there might be concreteC, concreteD etc. I dont mind adding mappings for more concrete classes

LightCZ
  • 695
  • 1
  • 8
  • 20
  • You can't map to an abstract class, AutoMapper creates a new instance of the class you are mapping to and as the error says you cannot instantiate an abstract class. Make your base class concrete and it will work, an abstract class is not appropriate because you do want to create instances of it. – Ben Robinson Sep 30 '14 at 12:41
  • Actually i dont want to create instance of DtoBase what i expect as return value from GetResourceDto is instance of concreteA_Dto. – LightCZ Sep 30 '14 at 12:43
  • When using automapper like this, the class hierarchies must match. If you create a base class in the "concrete" hierarchy, things should work fine. – Andrew Whitaker Sep 30 '14 at 13:26
  • thats just sad. Because sometime instead of my concreteB can come for an example instance of List and i want to transfare it in proper DTO with additional information. – LightCZ Sep 30 '14 at 13:34

1 Answers1

0

You might often have similar mapping problems unless you don't use surrogate classes for mapping.

Create surrogate classes for every class you would like to map.

You can get additional help from here

Community
  • 1
  • 1
aog
  • 484
  • 3
  • 14
  • Thanks i guess that from architectonical view there should be that surrogate classes and there should be that base class as Ben and Andrew pointed. I ll refactor my solution and add this part – LightCZ Oct 03 '14 at 14:45