3至4更新AutoMapper爆发继承映射 [英] Updated AutoMapper from 3 to 4 broke inheritance mapping
问题描述
我从3.3.1到4.0.4打破了下面的映射与此消息
更新AutoMapper
无法投类型的对象'富'输入'BarDTO
块引用>
类
公共类FooDTO
{
//省略
}
//衍生DTO
公类BarDTO:FooDTO
{
公共字符串额外{搞定;组; }
}
映射配置
Mapper.CreateMap<富,FooDTO方式>()ReverseMap();
Mapper.CreateMap<富,BarDTO>();
映射
地图<富,BarDTO>(富); //抛出异常投
我使用
.INCLUDE也试过()
方法,但并没有发挥作用。Mapper.CreateMap<富,FooDTO>()
&.INCLUDE LT;富,BarDTO>()
.ReverseMap();
Mapper.CreateMap<富,BarDTO>();
我做得不对,或者是一个错误吗?
< DIV CLASS =h2_lin>解决方案
这是一个已知的变化从3.xx的发生4.配置里面Mapper.Initialize映射可以解决这个问题。
例如。
在3.xx的映射是这样做的:
Mapper.CreateMap<令,OrderDto>()
&.INCLUDE LT;网上订单,OnlineOrderDto>()
&.INCLUDE LT;邮购,MailOrderDto>();
Mapper.CreateMap<网上订单,OnlineOrderDto>();
Mapper.CreateMap<邮购,MailOrderDto>();
现在,在4.xx的映射应该在初始化方法使用委托完成的。
Mapper.Initialize(CFG =>
{
cfg.CreateMap<令,OrderDto>()
.INCLUDE<网上订单,OnlineOrderDto>()
.INCLUDE<邮购,MailOrderDto>();
cfg.CreateMap<网上订单,OnlineOrderDto>();
cfg.CreateMap<邮购,MailOrderDto> ();
});
下面是相关的问题
更新版本:错误固定的4.1.0里程碑
块引用>
另外,你可以做的是密封的映射。
Mapper.Configuration.Seal();
I updated AutoMapper from 3.3.1 to 4.0.4 which broke the following mapping with this message
Unable to cast object of type 'Foo' to type '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.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.x.x to 4. Configuring the mapping inside Mapper.Initialize would solve the problem.
e.g. In 3.x.x mapping is done like this:
Mapper.CreateMap<Order, OrderDto>() .Include<OnlineOrder, OnlineOrderDto>() .Include<MailOrder, MailOrderDto>(); Mapper.CreateMap<OnlineOrder, OnlineOrderDto>(); Mapper.CreateMap<MailOrder, MailOrderDto>();
Now, In 4.x.x mapping should be done in Initialize method using delegate.
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
Alternatively, you can do is seal the mappings.
Mapper.Configuration.Seal();
这篇关于3至4更新AutoMapper爆发继承映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!