Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Automapper to map an object to an unknown destination type?

Tags:

c#

automapper

Consider the following scenario. I have a number of classes that share a common base class and I have defined an automapper mapping for each derived class. Something like this:

class A : Base {}

class B : Base {}

class ContractA : ContractBase {}

class ContractB : ContractBase {}

void Foo()
{
    Mapper.CreateMap<A, ContractA>();
    Mapper.CreateMap<B, ContractB>();
}

So far so good. But now I want to create a method like this:

ContractBase Foo()
{
    Base obj = GetObject();

    return Mapper.???
}

The problem is that all of AutoMapper's Map variants require that I either know the destination type at compile time or have an object of that type available at runtime. This is seriously frustrating since I have defined only one map for each source type. AutoMapper should be able to infer the destination type given only the source type.

Is there any good way around this? I want to avoid creating a dictionary mapping source types to destination types. While this would work, it would mean that I'd essentially have to define two mappings for every source type.

like image 213
Peter Ruderman Avatar asked Oct 05 '10 18:10

Peter Ruderman


People also ask

Does AutoMapper map private fields?

AutoMapper will map property with private setter with no problem. If you want to force encapsulation, you need to use IgnoreAllPropertiesWithAnInaccessibleSetter. With this option, all private properties (and other inaccessible) will be ignored.

Does AutoMapper map both ways?

Yes, or you can call CreateMap<ModelClass, ViewModelClass>(). ReverseMap() .

What is the use of AutoMapper in C#?

AutoMapper in C# is a library used to map data from one object to another. It acts as a mapper between two objects and transforms one object type into another. It converts the input object of one type to the output object of another type until the latter type follows or maintains the conventions of AutoMapper.


1 Answers

You could access the mappings stored in AutoMapper:

ContractBase Foo() {
  Base obj = GetObject();

  var sourceType = obj.GetType();
  var destinationType = Mapper.GetAllTypeMaps().
    Where(map => map.SourceType == sourceType).
    // Note: it's assumed that you only have one mapping for the source type!
    Single(). 
    DestinationType;

  return (ContractBase)Mapper.Map(obj, sourceType, destinationType);
}
like image 93
Jordão Avatar answered Nov 14 '22 23:11

Jordão