Mapster映射List中的派生类失效问题(C#)
解决Mapster映射基类集合时不使用派生类配置的问题
问题场景
我有多个继承自抽象基类Step的派生类,代码如下:
public abstract class Step { public StepId Id {get; set;} public string Text {get; set;} public StepType Type {get;set;} } public class SelectionStep : Step { public List<string> Selections {get; set;} } public class NumericStep : Step { }
配置了如下Mapster映射规则:
config.NewConfig<SelectionStep, StepResponse>() .Map(dest => dest.Selections, src => src.Selections.Select(x => x.Value)); config.NewConfig<Step, StepResponse>() .Map(dest => dest.Id, src => src.Id.Value.ToString()) .Map(dest => dest.Type, src => src.Type.ToString());
单独映射SelectionStep到StepResponse时可正常工作,但映射包含SelectionStep和NumericStep的List<Step>到List<StepResponse>时,SelectionStep对应的映射配置未被使用。
解决方案
要让Mapster在映射基类集合时自动识别派生类的映射规则,需要在基类的映射配置中显式包含派生类的映射关系,修改配置如下:
方式一:使用Include方法
// 保留派生类的原有映射配置 config.NewConfig<SelectionStep, StepResponse>() .Map(dest => dest.Selections, src => src.Selections.Select(x => x.Value)); // 在基类映射配置中添加Include,关联派生类的映射规则 config.NewConfig<Step, StepResponse>() .Map(dest => dest.Id, src => src.Id.Value.ToString()) .Map(dest => dest.Type, src => src.Type.ToString()) .Include<SelectionStep, StepResponse>(); // 关键配置行
方式二:使用PolymorphicType统一配置
config.ForType<Step, StepResponse>() .Map(dest => dest.Id, src => src.Id.Value.ToString()) .Map(dest => dest.Type, src => src.Type.ToString()) .PolymorphicType() .Add<SelectionStep, StepResponse>(cfg => cfg.Map(dest => dest.Selections, src => src.Selections.Select(x => x.Value)));
原因说明
Mapster处理基类对象集合时,默认只会应用基类的映射规则,不会自动关联派生类的独立配置。通过Include方法或PolymorphicType配置,我们明确告诉Mapster:当遇到Step类型的实例实际是SelectionStep时,要使用对应的派生类映射逻辑,这样集合中的SelectionStep就能正确映射Selections字段了。
内容的提问来源于stack exchange,提问作者Febre
相关产品推荐
相关产品推荐

