Get all the defined mappings from an AutoMapper defined mapping

Viewed 9521

Let's assume that I've two classes : CD and CDModel, and the mapping is defined as follows:

Mapper.CreateMap<CDModel, CD>()
        .ForMember(c => c.Name, opt => opt.MapFrom(m => m.Title));

Is there an easy way to retrieve the original expression like c => c.Name (for source) and m => m.Title (for destination) from the mapping?

I tried this, but I miss some things...

var map = Mapper.FindTypeMapFor<CDModel, CD>();
foreach (var propertMap in map.GetPropertyMaps())
{
    var source = ???;
    var dest = propertMap.DestinationProperty.MemberInfo;
}

How to get the source and destination expressions?

3 Answers

I'm using Automapper 7.0 and the syntax is different now. For example,

void Dump(TypeMap map)
{
    Console.WriteLine("---------------------------------------------------------------------");
    Console.WriteLine(map.SourceType + " ==> " + map.DestinationType);
    foreach (var m in map.GetPropertyMaps())
    {
        Console.WriteLine(m.SourceMember.Name + " ==> " + m.DestinationProperty.Name);
    }
}

And then you can call it using:

Dump(Mapper.Instance.ConfigurationProvider.FindTypeMapFor(typeof(CDModel), typeof(CD)));

or if you want to dump out everything, then do like this.

foreach (var map in Mapper.Instance.ConfigurationProvider.GetAllTypeMaps())
{
    Dump(map);
}
Related