Source/destination types
abstract class Vehicle
{
public int Id { get; set; }
public string Name { get; set; }
}
class Car : Vehicle
{
public int AmountDoors { get; set; }
}
class Motorcycle : Vehicle
{
public bool HasSidecar { get; set; }
}
class VehicleDto
{
public string Name { get; set; }
}
class MotorCycleDto : VehicleDto
{
public bool HasSidecar { get; set; }
}
Mapping configuration
cfg.CreateMap<Vehicle, VehicleDto>()
.IncludeAllDerived();
cfg.CreateMap<Motorcycle, MotorCycleDto>();
Version: 13.0.1
Expected behavior
mapper.ProjectTo<VehicleDto>(context.Cars).ToList();
with context.Cars being a DbSet of Cars should not throw an error.
Actual behavior
an error is thrown:
No coercion operator is defined between types 'Car' and 'Motorcycle'
Steps to reproduce
Gist
This code works in Automapper 12. The issue seems to be caused by there being an explicit mapping for one of the Vehicle subclasses, but not the other. Adding an explicit map fixes the issue.
cfg.CreateMap<Vehicle, VehicleDto>()
.IncludeAllDerived();
cfg.CreateMap<Motorcycle, MotorCycleDto>();
cfg.CreateMap<Car, VehicleDto>();
Removing the map from Motorcycle to MotorcycleDto also fixes the issue, allowing
mapper.ProjectTo<VehicleDto>(context.Cars).ToList();
to execute properly.