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();