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:
Now, In 4.x.x mapping should be done in Initialize method using delegate.
Here's the discussion related to the issue .
Alternatively, you can do is seal the mappings.