Reputation: 1176
I want to flatten my data structure to dto.
My source class (simplified) looks like:
public class DeliveryNote
{
public DeliveryNoteNested DeliveryNoteNestedInstance { get; set; }
public string VehicleNo { get; set; }
}
public class DeliveryNoteNested
{
public string No { get; set; }
public string PlantNo { get; set; }
}
My dto (simplified too) like
public class DeliveryNoteDto
{
public int Id { get; set; }
public string No { get; set; }
public string PlantNo { get; set; }
public string VehicleNo { get; set; }
}
And then I do my mapping:
Mapper.Initialize(cfg => cfg.CreateMap<DeliveryNote, DeliveryNoteDto>());
var source = new DeliveryNote
{
VehicleNo = "VehicleNo20",
DeliveryNoteNestedInstance = new DeliveryNoteNested
{
No = "42",
PlantNo = "PlantNo10"
}
};
var dto = Mapper.Map<DeliveryNoteDto>(source);
At the end I expecting my properties No and PlantNo are filled in the dto by naming convention, but they are not.
When I do
Mapper.Initialize(cfg => cfg.CreateMap<DeliveryNote, DeliveryNoteDto>()
.ForMember(dest => dest.No, opt => opt.MapFrom(src => src.DeliveryNoteNestedInstance.No))
.ForMember(dest => dest.PlantNo, opt => opt.MapFrom(src => src.DeliveryNoteNestedInstance.PlantNo)));
it works, but in my real class I have close to 50 properties and I would like to avoid such boiler plate code when possible.
Upvotes: 2
Views: 404
Reputation: 30665
You can also use
CreateMap(typeof(DeliveryNote), typeof(DeliveryNoteDto))
.AfterMap((s, d) => Mapper.Map(s.DeliveryNoteNested, d));
Upvotes: 0
Reputation: 273784
The basic convention would be
public class DeliveryNoteDto
{
public int Id { get; set; }
public string DeliveryNoteNestedInstanceNo { get; set; }
public string DeliveryNoteNestedInstancePlantNo { get; set; }
public string VehicleNo { get; set; }
}
Upvotes: 1