Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper: What is the difference between MapFrom and ResolveUsing?

Ignoring the ResolveUsing overloads that take an IValueResolver, and looking only at these 2 methods:

void ResolveUsing(Func<TSource, object> resolver); void MapFrom<TMember>(Expression<Func<TSource, TMember>> sourceMember); 

The main difference between these 2 seems to be that ResolveUsing takes a Func<TSource, object>, whereas MapFrom takes an Expression<Func<TSource, TMember>>.

However in client code that actually uses one of these methods with a lambda expression, they seem to be interchangeable:

Mapper.CreateMap<SourceType, DestType>() // uses ResolveUsing    .ForMember(d => d.DestPropX, o => o.ResolveUsing(s => s.SourcePropY));  Mapper.CreateMap<SourceType, DestType>() // uses MapFrom    .ForMember(d => d.DestPropX, o => o.MapFrom(s => s.SourcePropY)); 

So what ultimately is the difference between the above 2 choices? Is one faster than the other? Is one a better choice than the other and if so, when / why?

like image 330
danludwig Avatar asked Feb 14 '13 12:02

danludwig


People also ask

How do I use ForMember in AutoMapper?

CreateMap<EFAddress, Address>() . ForMember(dest => dest. Code, opt => opt. MapFrom(src => src.Name));

Does AutoMapper use reflection?

When you call CreateMap, AutoMapper uses optimizers to build the code for getting/setting values on source/destination types. Currently, it uses a combination of Reflection.

What is the AutoMapper?

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

In the past I had a long email exchange on the mailing list with the author of Automapper. MapFrom will do null checks all the way trough the expression:

So you can do opt => opt.MapFrom(src => src.SomeProp.Way.Down.Here.Somewhere) and each level will get checked for nulls (as it already does for flattening).

like image 89
Sunny Milenov Avatar answered Sep 21 '22 03:09

Sunny Milenov