Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all the defined mappings from an AutoMapper defined mapping

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?

like image 857
Stef Heyenrath Avatar asked Jul 25 '11 11:07

Stef Heyenrath


People also ask

How do I use AutoMapper to list a map?

Once you have your types, and a reference to AutoMapper, you can create a map for the two types. Mapper. CreateMap<Order, OrderDto>(); The type on the left is the source type, and the type on the right is the destination type.

Can AutoMapper map collections?

Polymorphic element types in collectionsAutoMapper supports polymorphic arrays and collections, such that derived source/destination types are used if found.

Does AutoMapper map private properties?

By default, AutoMapper only recognizes public members. It can map to private setters, but will skip internal/private methods and properties if the entire property is private/internal.


1 Answers

Going along the same path as what you were doing ...

foreach( var propertMap in map.GetPropertyMaps() )
{
    var dest = propertMap.DestinationProperty.MemberInfo;
    var source = propertMap.SourceMember;
}

How exactly do you want the expressions? Are you wanting the underlying Lambas?

If so look at

propertMap.GetSourceValueResolvers()
like image 112
Dave Walker Avatar answered Oct 02 '22 19:10

Dave Walker