Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using automapper change destination value only if it is equal to 0

Tags:

c#

automapper

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?

like image 901
Yuri Zolotarev Avatar asked Nov 15 '17 09:11

Yuri Zolotarev


People also ask

How do I ignore properties in AutoMapper?

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.

How does AutoMapper handle null?

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.

Is AutoMapper faster than manual mapping?

Automapper is considerably faster when mapping a List<T> of objects on . NET Core (It's still slower on full . NET Framework).

How does AutoMapper work internally?

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.


1 Answers

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);
     });
like image 152
Clark.Hsu Avatar answered Nov 14 '22 22:11

Clark.Hsu