2

Is it possible to use a custom value resolver in automapper only if a certain condition is met?

In my case I only want to update the value with the custom value resolver if the destination is not null.

This is an example of my code. Basically I need to add the condition onto this. Is it possible?

Mapper.CreateMap<ResponseXml, MyModel>()
    .ForMember(dest => dest.FirstName, 
                 op => op.ResolveUsing<ResponseXmlValueResolver>()
                .FromMember(x => x.data.FirstOrDefault(y => y.name == "name")))
stuartd
  • 70,509
  • 14
  • 132
  • 163
user441365
  • 3,934
  • 11
  • 43
  • 62

3 Answers3

1

I think Eris' solution would have work; It was just grammatical errors.

Mapper.CreateMap<ResponseXml, MyModel>()
    .ForMember(dest => dest.FirstName, 
             op => {
                    op.Condition(src => src != null);
                    op.ResolveUsing<ResponseXmlValueResolver>();
                      .FromMember(x => x.data.FirstOrDefault(y => y.name == "name"));
             });

Is this what you wanted?
If the destination is null, the mapping will be ignore.
If the destination is null, the mapping (with the customer resolved) will be apply.

an phu
  • 1,823
  • 1
  • 16
  • 10
  • This is not correct because conditions are evaluated *AFTER* resolving value as stated here https://github.com/AutoMapper/AutoMapper/wiki/Resolvers-and-conditions – A77 Aug 24 '22 at 18:42
0

As Conditions are evaluated after resolving member, like it's said here, none of the previous answers are correct. You should rather use PreCondition this way:

Mapper.CreateMap<ResponseXml, MyModel>()
.ForMember(dest => dest.FirstName, 
         op => {
                op.PreCondition(src => src != null);
                op.ResolveUsing<ResponseXmlValueResolver>();
                  .FromMember(x => x.data.FirstOrDefault(y => y.name == "name"));
         });
A77
  • 172
  • 1
  • 7
-1

Will this work? (I don't have a windows box in front of me at the moment)

Mapper.CreateMap<ResponseXml, MyModel>()
    .ForMember(dest => dest.FirstName, 
             op => op.Condition(src => src != null)
                     .ResolveUsing<ResponseXmlValueResolver>()
                     .FromMember(x => x.data.FirstOrDefault(y => y.name == "name")))
Eris
  • 7,378
  • 1
  • 30
  • 45