Automapper:如何将复杂对象展平为普通对象

时间:2019-01-24 12:31:04

标签: c# automapper automapper-8

 public class Complex
{
    public A A { get; set; }
    public A B { get; set; }
}

public class A
{
    public int a1 { get; set; }
    public int a2 { get; set; }
}

public class B
{
    public int b1 { get; set; }
    public int b2 { get; set; }
}
//----------------Source Object End Here---------------------

public class Simple  <----[This Simple class has only properties of A class]
{
    public int aa1 { get; set; }
    public int aa2 { get; set; }
}
//----------------Destination Object End Here---------------------

CreateMap<A, Simple>()
    .ForMember(dest => dest.aa1, opt => opt.MapFrom(src => src.a1))
    .ForMember(dest => dest.aa2, opt => opt.MapFrom(src => src.a2))

// Mapper IS NOT AVAILABLE HERE AS I AM USING PROFILE BASED CONFIGURATION
CreateMap<Complex, Simple>()
    .ConvertUsing(src => Mapper.Map<A, Simple>(src.A)); <------Error at this line

//----------------Automammer config End Here---------------------

如何将Complex变平为Simple?我不希望在Complex.ASimple的配置中一次又一次地将Complex映射到Simple,因为上面已经对其进行了配置。

1 个答案:

答案 0 :(得分:0)

最后,我想出了ConvertUsing

的另一种重载方法。
CreateMap<Complex, Simple>()
.ConvertUsing((src,ctx) => {
     return ctx.Mapper.Map<Complex, Simple>(src.A)
}); 

我觉得这种重载方法具有多种可能性和灵活性。如问题中所述,我没有直接访问Mapper的问题。此重载方法具有其自己的上下文参数(ResolutionContext)。我们可以从此上下文参数中使用Mapper,例如ctx.Mapper.Map<Complex, Simple>(src.A)