1

I have a scenario like

If total number of days is less than 30 days, then I have to set Salary to null

this.CreateMap<Foo, Doo>()
    .ForMember(dst => dst.Salary, opt => {
                              opt.Condition(src => src.JoinedDate.Days <= 30));
                              opt.MapFrom(null)
}

But I am facing error "cannot find member of type Foo. Parameter name: name". but don't have any property "name".

Question is How to pass null value to destination property in condition check, and retain existing value if days greater than 30.

opt.MapFrom(null)

3 Answers 3

2

Try using:

this.CreateMap<Foo, Doo>()
    .ForMember(dst => dst.Salary, 
        opt => opt.MapFrom(src => src.JoinedDate.Days <= 30 ? null : src.Salary))

UPD

To preserve Salary from destination use overload of MapFrom accepting both source and destination:

this.CreateMap<Foo, Doo>()
    .ForMember(dst => dst.Salary, 
        opt => opt.MapFrom((src, dst) => src.JoinedDate.Days <= 30 ? null : dst.Salary))
Sign up to request clarification or add additional context in comments.

3 Comments

If condition fails, then I have to retain my existing Salary. so which means : src.Salary supposed to be dst.Salary, but it is inaccessible
@Munijagadish what version are you using? Latest one works fine for me.
Mine is not last version, However both above answers helped to figure out solution.. I will add answer
1

You can use automapper inline ResolveUsing.

ForMember(dst => dst.Salary,
            o => o.ResolveUsing(src => src.JoinedDate.Days > 30 ? src.Salary: null));

1 Comment

If condition fails, then I have to retain my existing Salary. so which means : src.Salary supposed to be dst.Salary, but it is inaccessible
1

I just combined above two solutions and found answer for my question.

ForMember(dst => dst.Salary,
            opt => opt.ResolveUsing((src, dst) => src.JoinedDate.Days <= 30 ? null: dst.Salary));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.