I map my objects to DTO using AutoMapper. Some of my objects have virtual properties that can be overridden by derived objects. I map virtual properties using the base classes in which they are defined. However, when mapping derived classes, AutoMapper maps the base implementation of the virtual properties instead of the overridden one.
I will start with 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 display 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);
CreateMap, , . 20 , , , .
AutoMapper?