AutoMapper:MapFrom和ResolveUsing有什么区别? [英] AutoMapper: What is the difference between MapFrom and ResolveUsing?
问题描述
忽略采用IValueResolver的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);
这2个之间的主要区别似乎是ResolveUsing
带有Func<TSource, object>
,而MapFrom带有Expression<Func<TSource, TMember>>
.
The main difference between these 2 seems to be that ResolveUsing
takes a Func<TSource, object>
, whereas MapFrom takes an Expression<Func<TSource, TMember>>
.
但是在实际使用以下方法之一和lambda表达式的客户端代码中,它们似乎是可互换的:
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?
推荐答案
过去,我有一个在邮件列表上与Automapper的作者进行长时间的电子邮件交换. MapFrom将通过表达式一直执行空检查:
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:
因此您可以执行
opt => opt.MapFrom(src => src.SomeProp.Way.Down.Here.Somewhere)
,每个级别都会被检查 为null(就像它已经为扁平化所做的那样.)
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).
这篇关于AutoMapper:MapFrom和ResolveUsing有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!