c# - AutoMapper 子对象中没有前缀名称的展平

标签 c# automapper

将这些类视为源:

public class SourceParent
{
    public int X { get; set; }
    public SourceChild1 Child1 { get; set; }
    public SourceChild2 Child2 { get; set; }
}

public class SourceChild1
{
    public int A { get; set; }
    public int B { get; set; }
    public int C { get; set; }
    public int D { get; set; }
}

public class SourceChild2
{
    public int I { get; set; }
    public int J { get; set; }
    public int K { get; set; }
    public int L { get; set; }
}

我正在尝试将源映射到与此类似的目的地:

public class Destination
{
    public int X { get; set; }

    public int A { get; set; }
    public int B { get; set; }
    public int C { get; set; }
    public int D { get; set; }

    public int I { get; set; }
    public int J { get; set; }
    public int K { get; set; }
    public int L { get; set; }
}

好吧,使用这个配置,可以进行映射:

Mapper.CreateMap<SourceParent, Destination>()
    .ForMember(d => d.A, opt => opt.MapFrom(s => s.Child1.A))
    .ForMember(d => d.B, opt => opt.MapFrom(s => s.Child1.B))
    .ForMember(d => d.C, opt => opt.MapFrom(s => s.Child1.C))
    .ForMember(d => d.D, opt => opt.MapFrom(s => s.Child1.D))
    .ForMember(d => d.I, opt => opt.MapFrom(s => s.Child2.I))
    .ForMember(d => d.J, opt => opt.MapFrom(s => s.Child2.J))
    .ForMember(d => d.K, opt => opt.MapFrom(s => s.Child2.K))
    .ForMember(d => d.L, opt => opt.MapFrom(s => s.Child2.L));

除非子类有许多属性,并且所有属性都与父类同名,否则这不是一种干净的方法。

理想情况下,我想告诉 AutoMapper 也将 Source.Child1 和 Source.Child2 作为源,并将每个匹配的属性名称映射到目标(而不是指定每个属性);像这样:

Mapper.CreateMap<SourceParent, Destination>()
    .AlsoUseSource(s => s.Child1)
    .AlsoUseSource(s => s.Child2);

最佳答案

您可以使用 .ConstructUsing 来完成此操作。它不是世界上看起来最干净的东西,但它会起作用:

/* Map each child to the destination */
Mapper.CreateMap<SourceChild1, Destination>();
Mapper.CreateMap<SourceChild2, Destination>();

Mapper.CreateMap<SourceParent, Destination>()
    .ConstructUsing(src =>
    {
        /* Map A-D from Child1 */
        var dest = Mapper.Map<Destination>(src.Child1);

        /* Map I-L from Child2 */
        Mapper.Map(src.Child2, dest);

        return dest;
    });
/* X will be mapped automatically. */

这应该会成功映射所有属性。

不幸的是,对 .AssertConfigurationIsValid 的调用将失败,因为属性 I - L 不会映射到映射的目标类型从 SourceParentDestination

当然,您可以为每个调用编写对 .Ignore 的调用,但这会破坏摆脱嵌套映射调用的目的。

您的另一个选择是利用 this awesome answer忽略每个映射上未映射的属性。

关于c# - AutoMapper 子对象中没有前缀名称的展平,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26841112/

相关文章:

c# - 从 appsettings.json 到选项的绑定(bind)部分

c# - 我可以在其上安装 IDE(集成开发环境)如 Visual Studio、Net-beans 的移动设备或 PDA

c# - 如何将通用配置文件与 Automapper 和 Asp.Net Core 依赖注入(inject)一起使用

c# - AutoMapper 并将日期时间转换为字符串

c# - 在模拟方法(Moq)中更改引用参数的值

c# - Exchange Web 服务 - 使用资源创建约会但与会者看不到资源

c# - 是否有一种类型的对象,我可以将 Buttons 和 MenuItem 对象都转换到该对象以访问它们的 Tag 属性?

entity-framework - 在 AutoMapper 8.0 中缺少 ResolveUsing

c# - Automapper:处理对象到对象映射的可空属性

c# - WebAPI Controller 中的自动映射器