2017-04-12 131 views
0

我一直在嘗試使用AutoMapper,但是我在配置地圖時遇到了問題。AutoMapper地圖複雜對象

有了這個:

public class A 
{ 
    public B b { get; set; } 
    public C c { get; set; } 
    public int id { get; set; } 
    public string X { get; set; } 
} 

public class B 
{ 
    public int id { get; set; } 
    public string Y { get; set; } 
} 

public class C 
{ 
    public int id { get; set; } 
    public string Z { get; set; } 
} 

public class ABC 
{ 
    public int Aid { get; set; } 
    public string AX { get; set; } 
    public int Bid { get; set; } 
    public string BY { get; set; } 
    public int Cid { get; set; } 
    public string CZ { get; set; } 
} 

我如何做映射A> ABC和ABC> A.

我不希望每個屬性手動映射。可能嗎?

謝謝。

+0

通常,automapper要求屬性名稱相同。對於需要配置映射的不同名稱。所以在你的情況下,你必須在automapper中映射每個屬性。 –

+0

如何更改不必配置映射? – user2653142

回答

1

我不確定你的意思是「我不想手動映射每個屬性」。但使用AutoMapper,您可以輕鬆映射屬性:

 Mapper.Initialize(cfg => cfg.CreateMap<A, ABC>() 
      .ForMember(dest => dest.AX, opt => opt.MapFrom(src => src.X)) 
      .ForMember(dest => dest.Aid, opt => opt.MapFrom(src => src.id)) 
      .ForMember(dest => dest.BY, opt => opt.MapFrom(src => src.b.Y)) 
      .ForMember(dest => dest.Bid, opt => opt.MapFrom(src => src.b.id)) 
      .ForMember(dest => dest.CZ, opt => opt.MapFrom(src => src.c.Z)) 
      .ForMember(dest => dest.Cid, opt => opt.MapFrom(src => src.c.id))); 

     var a = new A 
     { 
      X = "I am A", 
      id = 0, 
      b = new B() 
      { 
       Y = "I am B", 
       id = 1 
      }, 
      c = new C() 
      { 
       Z = "I am C", 
       id = 2 
      } 
     }; 

     var abc = Mapper.Map<A, ABC>(a); 
+0

是否可以設置一些映射規則?有很多屬性... – user2653142