Reputation: 31
I have defined a mapping from one type to DTO. Another type references the first type as an property, but the output should be an flattened DTO that should use the already defined mapping for the first type.
class Program {
static void Main(string[] args) {
var mapperConfiguration = new MapperConfiguration(cfg => {
cfg.CreateMap<FirstDataType,
FirstTypeDto>().ForMember(d => d.TypeResult, opt => opt.MapFrom(s => s.ToString()));
/* HOW TO CONFIGURE MAPPING OF THE 'FirstData' PROPERTY TO USE THE ABOVE DEFINED MAPPING
cfg.CreateMap<SecondDataType, SecondTypeDto>()
*/
});
var firstData = new FirstDataType {
TypeName = "TestType",
TypeValue = "TestValue"
};
var secondData = new SecondDataType {
Id = 1,
Name = "Second type",
FirstData = firstData
};
var mapper = mapperConfiguration.CreateMapper();
var firstDto = mapper.Map<FirstTypeDto>(firstData);
var secondDto = mapper.Map<SecondTypeDto>(secondData);
Console.ReadKey(true);
}
}
public class FirstDataType {
public string TypeName {
get;
set;
}
public string TypeValue {
get;
set;
}
public override string ToString() {
return $ "{TypeName}: {TypeValue}";
}
}
public class SecondDataType {
public int Id {
get;
set;
}
public string Name {
get;
set;
}
public FirstDataType FirstData {
get;
set;
}
}
public class FirstTypeDto {
public string TypeName {
get;
set;
}
public string TypeValue {
get;
set;
}
public string TypeResult {
get;
set;
}
}
public class SecondTypeDto: FirstTypeDto {
public int Id {
get;
set;
}
public string Name {
get;
set;
}
}
How should I configure mapping for the second type to use the defined mapping for the property 'FirstData'?
Thanks!
Upvotes: 1
Views: 1468
Reputation: 31
First, credit goes to Lucian Bargaoanu for leading me in the right direction. Basically, you need to create a mapping from the source to the destination derived type, but just include the existing mapping.
cfg.CreateMap<FirstDataType, SecondTypeDto>()
.IncludeBase<FirstDataType, FirstTypeDto>()
.ReverseMap();
cfg.CreateMap<SecondDataType, SecondTypeDto>()
.IncludeMembers(s => s.FirstData)
.ReverseMap();
Upvotes: 1