[英]Updated AutoMapper from 3 to 4 broke inheritance mapping
I updated AutoMapper from 3.3.1 to 4.0.4 which broke the following mapping with this message 我将AutoMapper从3.3.1更新到4.0.4,这打破了以下映射与此消息
Unable to cast object of type 'Foo' to type 'BarDTO'
无法将“Foo”类型的对象强制转换为“BarDTO”类型
Classes 类
public class FooDTO
{
// omitted
}
// derived DTO
public class BarDTO : FooDTO
{
public string Extra { get; set; }
}
Mapping config 映射配置
Mapper.CreateMap<Foo, FooDTO>().ReverseMap();
Mapper.CreateMap<Foo, BarDTO>();
Mapping 制图
Map<Foo, BarDTO>(foo); // throws cast exception
I also tried using the .Include()
method, but didn't make a difference. 我也尝试过使用
.Include()
方法,但没有什么区别。
Mapper.CreateMap<Foo, FooDTO>()
.Include<Foo, BarDTO>()
.ReverseMap();
Mapper.CreateMap<Foo, BarDTO>();
Am I doing something wrong, or is it a bug? 我做错了什么,还是一个错误?
This is a known change happened from 3.xx to 4. Configuring the mapping inside Mapper.Initialize would solve the problem. 这是从3.xx到4发生的已知变化。在Mapper.Initialize中配置映射可以解决问题。
eg In 3.xx mapping is done like this: 例如,3.xx映射是这样完成的:
Mapper.CreateMap<Order, OrderDto>()
.Include<OnlineOrder, OnlineOrderDto>()
.Include<MailOrder, MailOrderDto>();
Mapper.CreateMap<OnlineOrder, OnlineOrderDto>();
Mapper.CreateMap<MailOrder, MailOrderDto>();
Now, In 4.xx mapping should be done in Initialize method using delegate. 现在,在4.xx中,映射应该在使用委托的Initialize方法中完成。
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Order, OrderDto>()
.Include<OnlineOrder, OnlineOrderDto>()
.Include<MailOrder, MailOrderDto>();
cfg.CreateMap<OnlineOrder, OnlineOrderDto>();
cfg.CreateMap<MailOrder, MailOrderDto>();
});
Here's the discussion related to the issue . 以下是与该问题相关的讨论。
Update ver: bug fixed for 4.1.0 milestone
更新版本:针对4.1.0里程碑修复的错误
Alternatively, you can do is seal the mappings. 或者,您可以做的是密封映射。
Mapper.Configuration.Seal();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.