I have, in my opinion, a very common scenario using AutoMapper, which is an attempt to dynamically match a forecast so as not to query the database for columns that I will not use:
var map = Mapper.CreateMap<Source, DestinationViewModel>(); map.ForAllMembers(opt => opt.Ignore()); if (conditionForFieldA) map.ForMember(vm => vm.FieldA, conf => conf.MapFrom(src => src.FieldAbc)); if (conditionForFieldB) map.ForMember(vm => vm.FieldB, conf => conf.MapFrom(src => src.FieldDef)); if (conditionForFieldC) map.ForMember(vm => vm.FieldC, conf => conf.MapFrom(src => src.FieldGhi));
It seems that the problem is that AutoMapper will cache the Source and DestinationViewModel mapping settings and will not accept / consider different mappings in addition. This causes a problem that I encountered: sometimes it will have conditionForFieldA, and sometimes it will not; regardless of this simple logic, it will only query the database for the same columns that were designed after the first Mapper.CreateMap was called.
Since the ASP.NET Web API project, Mapper.Reset () does not seem to be a good choice, since AutoMapper is set up only once (Application_Start ()), but it would be great if I could only reset this setting for very specific mappings .
Has anyone come across a script like this and been able to solve it with AutoMapper before?
Thanks!
source share