1

Can't use Mapping Inheritance and TypeConverter together.

I have this code:

/* BaseClassTypeConverter.cs */
public class BaseClassTypeConverter : ITypeConverter<SourceClass, BaseClass> {
    public BaseClass Convert(ResolutionContext context) {
        if (context == null || context.IsSourceValueNull)
            return null;

        var src = (SourceClass)context.SourceValue;

        return new BaseClass() {
            CommonAttr = src.SourceAttr
        };
    }
}

/* AutoMapperConfig.cs */
public static class AutoMapperConfig {

    public static void RegisterMappings() {
        AutoMapper.Mapper.Initialize(config => {
            config
                .CreateMap<SourceClass, BaseClass>()
                .Include<SourceClass, DerivedClass1>()
                .Include<SourceClass, DerivedClass2>()  
                .ForMember(dest => dest.CommonAttr, o => o.MapFrom(src => src.SourceAttr));
                //.ConvertUsing<BaseClassTypeConverter>(); //  NOT WORKING

            config
                .CreateMap<SourceClass, DerivedClass1>()
                .ForMember(dest => dest.Dummy, o => o.MapFrom(src => src.SourceAttr2))
                .IncludeBase<SourceClass, BaseClass>();
        });
    }
}

As you can see, I want to be able to map from a TypeConverter class, because I have some more complex computations to do, not just assign values as above.

When I use the type converter the mappings don't work, however when I remove the ConvertUsing and use inline mapping with ForMember all works just fine.

It is something I'm missing?

PD. I'm using: AutoMapper: version="4.2.1", targetFramework="net452"

1 Answer 1

4

Nope, you can't combine ConvertUsing and anything else. Once you use a custom type converter, the mapping is then completely up to you. That's why "ConvertUsing" returns "void", that's a signal saying "you're done with config thank you".

However, you CAN use ConstructUsing to build out the initial destination object. Or a custom AfterMap, that's also inherited. Just not ConvertUsing.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer!

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.