1

Mapping:

 .ForMember(dest => dest.DisplayName, opt => { opt.PreCondition(location => location.Parent != null); opt.MapFrom(src => src.Name + ", " + src.Parent.Name); }) .ForMember(dest => dest.DisplayName, opt => { opt.PreCondition((src, dest, context) => dest.DisplayName == null); opt.MapFrom(src => src.Name); }) 

Expected result:
If the first condition is met don't override the mapping.

What actually happens:
The second mapping is overriding the first mapping.

How can I solve this?

1
  • So what you’re mapping meets both conditions? Can you add the item you’re mapping to your example? Commented Aug 30, 2020 at 14:55

2 Answers 2

3

It doesn't work because you are overwriting previous mapping expressions calling another ForMember() for the same member, which is your case is DisplayName. Consider such case:

.ForMember(d => d.DisplayName, o => o.MapFrom(s => "1")) .ForMember(d => d.DisplayName, o => o.MapFrom(s => "2")) .ForMember(d => d.DisplayName, o => o.MapFrom(s => "3")); 

Which value will be mapped to DisplayName?

3

So in your case, your first conditional mapping expression is overwriten by the second one. To make it work, join the conditional mapping into one mapping expression:

.ForMember( dest => dest.DisplayName, opts => opts.MapFrom((src, dest) => { if (src.Parent != null) { return string.Join(", ", src.Name, src.Parent.Name); } else { if (dest.DisplayName is null) { return src.Name; } else { return "Some other value when no conditions were met."; } } })); 
Sign up to request clarification or add additional context in comments.

4 Comments

The example is not accurate because I added a condition to the destination, I was looking for something out of the box...
I am checking the destination too, see if (dest.DisplayName is null). Also, you didn't mention you were looking for solutions "out of the box" in stated question. The core answer is still valid - you can't stack ForMember() methods for the same member.
Can you show how it is not accurate? Based on your question, this answer looks correct with the exception of the string.join bit, which is simple enough to fix. Can you show what your result was when you tried this?
@reynoldsbj Thanks for the string.join notice, added missing seperator.
1

It would be a cool feature to have but I don't see it anywhere in Automapper documentation.

This should however work in your case if the logic is not more complex.

 .ForMember(dest => dest.DisplayName, opt => { opt.MapFrom(src => src.Name + (location.Parent != null ? ", " + src.Parent.Name : null)); }) 

1 Comment

I thought there is might be something out of the box...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.