I am trying to make Automapper change dsetination value only if it equals to a specific value. So I don't care what the source value is I just want to look at the destination value before mapping and if it equals to 0 then I want to do the mapping if it is >0 then I don't want to map this.
So far I can only come up with a method that does this but the other way around. It looks at the source and if the source value satisfies the condition it will map. Looks like this:
CreateMap<SurveyResource, Survey>()
.ForMember(dest => dest.ClientId, opt =>
{
opt.Condition(src => src.ClientId == 0);
opt.MapFrom(src => src.ClientId);
});
This will look as SurveyResource ClientId value and if it equals to 0 then it will paste 0 into the destination (ie. it will paste current source value of client id). Does anybody know how to do this the other way around? Do I have to use custom value resolvers?
So, the AutoMapper Ignore() method is used when you want to completely ignore the property in the mapping. The ignored property could be in either the source or the destination object.
The Null substitution allows us to supply an alternate value for a destination member if the source value is null. That means instead of mapping the null value from the source object, it will map from the value we supply.
Automapper is considerably faster when mapping a List<T> of objects on . NET Core (It's still slower on full . NET Framework).
How AutoMapper works? AutoMapper internally uses a great concept of programming called Reflection. Reflection in C# is used to retrieve metadata on types at runtime. With the help of Reflection, we can dynamically get a type of existing objects and invoke its methods or access its fields and properties.
Man, you are so close!
CreateMap<SurveyResource, Survey>()
.ForMember(dest => dest.ClientId, opt =>
{
opt.Condition((src, dest) => dest.ClientId == 0);// suppose dest is not null.
opt.MapFrom(src => src.ClientId);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With