Automapper - Inheritance mapper not working with type converter

我与影子孤独终老i 提交于 2019-12-04 05:50:12

问题


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:


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.



来源:https://stackoverflow.com/questions/37448383/automapper-inheritance-mapper-not-working-with-type-converter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!