更新了AutoMapper从3到4打破了inheritance映射
我将AutoMapper从3.3.1更新到4.0.4,这打破了以下映射与此消息
无法将’Foo’类型的对象强制转换为’BarDTO’类型
类
public class FooDTO { // omitted } // derived DTO public class BarDTO : FooDTO { public string Extra { get; set; } }
映射配置
Mapper.CreateMap().ReverseMap(); Mapper.CreateMap();
制图
Map(foo); // throws cast exception
我也尝试过使用.Include()
方法,但没有什么区别。
Mapper.CreateMap() .Include() .ReverseMap(); Mapper.CreateMap();
我做错了什么,还是一个错误?
这是从3.xx到4发生的已知变化。在Mapper.Initialize中配置映射可以解决问题。
例如,3.xx映射是这样完成的:
Mapper.CreateMap() .Include() .Include(); Mapper.CreateMap(); Mapper.CreateMap();
现在,在4.xx中,映射应该在使用委托的Initialize方法中完成。
Mapper.Initialize(cfg => { cfg.CreateMap() .Include() .Include(); cfg.CreateMap(); cfg.CreateMap(); });
以下是与该问题相关的讨论。
更新版本:针对4.1.0里程碑修复的错误
或者,您可以做的是密封映射。
Mapper.Configuration.Seal();