自动映射器:按属性命名约定变平不起作用

时间:2019-02-05 15:39:11

标签: c# .net-core automapper

我想将数据结构展平为dto。

我的源类(简化)如下:

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

我的dto(也简化了)

public class DeliveryNoteDto
{
    public int Id { get; set; }
    public string No { get; set; }
    public string PlantNo { get; set; }
    public string VehicleNo { get; set; }
}

然后我进行映射:

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

最后,我希望我的属性No和PlantNo通过命名约定在dto中填充,但实际上不是。

当我这样做

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

它可以工作,但是在我的真实课堂上,我拥有接近50个属性,并且我希望尽可能避免使用这种样板代码。

2 个答案:

答案 0 :(得分:1)

基本约定为

public class DeliveryNoteDto
{
    public int Id { get; set; }
    public string DeliveryNoteNestedInstanceNo { get; set; }
    public string DeliveryNoteNestedInstancePlantNo { get; set; }
    public string VehicleNo { get; set; }
}

答案 1 :(得分:0)

您也可以使用

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