简体   繁体   中英

Automapper: Flattening by properties naming convention does not work

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.

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; }
}

You can also use

 CreateMap(typeof(DeliveryNote), typeof(DeliveryNoteDto))
     .AfterMap((s, d) => Mapper.Map(s.DeliveryNoteNested, d));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM