Automapper-继承映射器不适用于类型转换器 [英] Automapper - Inheritance mapper not working with type converter
问题描述
不能同时使用映射继承和TypeConverter.
Can't use Mapping Inheritance and TypeConverter together.
我有此代码:
/* 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>();
});
}
}
如您所见,我希望能够从TypeConverter类进行映射,因为我要做一些更复杂的计算,而不仅仅是如上所述的赋值.
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.
当我使用类型转换器时,映射不起作用,但是当我删除ConvertUsing并在ForMember中使用内联映射时,一切都很好.
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.
这是我想念的东西吗?
PD.我正在使用:AutoMapper:version ="4.2.1",targetFramework ="net452"
PD. I'm using: AutoMapper: version="4.2.1", targetFramework="net452"
推荐答案
不,您不能将ConvertUsing与其他任何东西组合使用.使用自定义类型转换器后,映射就完全取决于您了.这就是"ConvertUsing"返回"void"的原因,这是一个信号,表明您已经完成了配置谢谢".
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".
但是,您可以使用ConstructUsing来构建初始目标对象.或自定义的AfterMap,它也是继承的.只是不使用ConvertUsing.
However, you CAN use ConstructUsing to build out the initial destination object. Or a custom AfterMap, that's also inherited. Just not ConvertUsing.
这篇关于Automapper-继承映射器不适用于类型转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!