I'm mapping my entities to DTOs, using AutoMapper. Some of my entities have virtual properties that may be overridden by derived entities. I'm mapping the virtual properties using the base classes they're defined in. However, when mapping the derived classes, AutoMapper maps the base implementation of the virtual properties instead of the overridden one.
I'll start with the class definitions:
public class BaseType
{
public virtual string Title
{
get { return string.Empty; }
}
}
public class DerivedType : BaseType
{
public override string Title
{
get { return Name; }
}
public string Name { get; set; }
}
public class BaseTypeDto
{
public string Title { get; set; }
}
public class DerivedTypeDto : BaseTypeDto
{
public string Name { get; set; }
}
Now for the mapping configuration:
CreateMap<BaseType, BaseTypeDto>()
.ForMember(n => n.Title, p => p.MapFrom(q => q.Title ?? "-"))
.Include<DerivedType, DerivedTypeDto>();
CreateMap<DerivedType, DerivedTypeDto>()
And finally the mapping:
DerivedTypeDto dto = Mapper.Map<DerivedType, DerivedTypeDto>(instance);
When I put the Title mapping on the CreateMap call that configures the derived type, it works. But since I have about 20 derived types, I really want the Title mapping to be configured on the base class, not having to repeat it for each derived class.
Is this possible with AutoMapper?