Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper: Conditional mapping based on Source object and ResolutionContext

Tags:

c#

automapper

I need to make a conditional mapping based on both the source object and ResolutionContext. Here is my code:

AutoMapper.Mapper.CreateMap<SourceType, DestinationType>()
    .ForMember(dest => dest.Value, opt =>
        {
            opt.Condition(context=>
                {
                    bool condition1 = (bool)context.Options.Items["Condition"];
                    bool condition2 = SomeFunction(context.SourceValue);
                    return !(condition1 && !condition2);
                });
            opt.MapFrom(src => src.Value);
        });

Unfortunately, this breaks because context.SourceValue is returning a String (not a SourceType). I thought that context.SourceValue returned the source object, but this doesn't seem to be the case.

Is there any way to do conditional mapping based on both the ResolutionContext and the Source object?

like image 541
asemahle Avatar asked Dec 20 '25 01:12

asemahle


1 Answers

context.SourceValue returns the member currently being converted, which in this case is SourceType.Value (which I guess is a string).

To obtain the SourceType object, use the following:

SourceType source_object = (SourceType)context.Parent.SourceValue;
like image 161
Yacoub Massad Avatar answered Dec 22 '25 14:12

Yacoub Massad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!