【问题标题】:Automapper: Flattening by properties naming convention does not workAutomapper:按属性命名约定展平不起作用
【发布时间】:2019-02-05 15:39:11
【问题描述】:

我想将我的数据结构展平为 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 个属性,我希望尽可能避免使用此类样板代码。

【问题讨论】:

  • 当父对象被映射时,您可以在 foreach 中映射子对象。
  • 在这种情况下,您可以使用反射来映射每个属性
  • @RossBush:你能用一些示例代码解释一下你的评论吗?
  • @SemenMiroshnichenko - 忽略,我认为您的 dto 是作为父/子创建的。与 dto 不同的是您的 poco 对象,这与我上面的评论相反。但是,这并不能回答您的问题,如果您创建尽可能接近数据库模式的域对象,减去不重要的字段。它使跨越边界变得不那么麻烦:)

标签: c# .net-core automapper


【解决方案1】:

基本约定是

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

【讨论】:

    【解决方案2】:

    你也可以使用

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

    【讨论】:

    • 对于 AutoMapper 8.0.0,我必须在示例代码中将 DeliveryNoteNested 替换为 DeliveryNoteNestedInstance,否则会出现编译错误。之后,Dto 中的所有字段都用“.DeliveryNoteNested”填充,也以类型名称作为值。所以它不起作用。
    • 和之前一样,我需要用 DeliveryNoteNestedInstance 替换 DeliveryNoteNested,当我这样做时,我得到异常“未映射的成员被发现 Unmapped properties: Id VehicleNo”
    • 在这种情况下,我相信您的命名不匹配。如果内部对象的命名不同,则需要使用 MapMember 单独映射它们。例如:source.Vehicle => dest.nestedObj.VehicleId 不能在不使用 MapMember 的情况下进行映射
    • 是的,我可以这样做(正如我在问题中提到的那样),但我正在寻找更优雅的解决方案(否则我必须以这种方式映射我所有的 50 个属性)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多