Reputation: 2311
I'm trying to map 2 classes inheriting different base (but with common property). When I use Map, parent properties doesn't map automatically (which I think should based on inhertiance laws). Please suggest if I'm wrong somewhere:
public class SourceBase
{
public bool IsSuccess { get; set; }
}
public class DestBase
{
public bool Success { get; set; }
}
public class ChildSource : SourceBase
{
public string SourceName { get; set; }
}
public class ChildDest : DestBase
{
public string DestName { get; set; }
}
Creating Maps
AutoMapper.Mapper.CreateMap<SourceBase, DestBase>()
.ForMember(dest => dest.Success, opt => opt.MapFrom(source => source.IsSuccess));
AutoMapper.Mapper.CreateMap<ChildSource, ChildDest>()
.ForMember(dest => dest.DestName,opt=>opt.MapFrom(source=>source.SourceName));
Using the Map
ChildSource ch = new ChildSource()
{
IsSuccess = true,
SourceName = "user1"
};
var obj = AutoMapper.Mapper.Map<ChildDest>(ch);
I expected IsSuccess as True and DestName as user1. But only SourceName gets set and IsSuccess remains false. If I use same name (IsSuccess) in both, it works which is because of automapping via name. But How can I use the existing format of different property names (but same types) in different class. I do not want to explicitly map parent properties while writing map for each child class.
Upvotes: 0
Views: 96
Reputation: 27986
You need to tell AutoMapper about the inheritance by using the Include method:
Mapper.CreateMap<SourceBase, DestBase>()
.Include<ChildSource, ChildDest>()
.ForMember(dest => dest.Success, opt => opt.MapFrom(source => source.IsSuccess));
Upvotes: 1