2012-02-02 160 views
4

什麼是內對象與Automapper 2.0Automapper地圖嵌套對象

  1. 映射使用溶液在此question(Automapper 1.0)

  2. 創建自定義值解析器的最佳方式

  3. public class DTOObject 
    { 
        // MainObject 
        public int Id { get; set; } 
        public string Name { get; set; } 
    
        // SubObject (TopObject) 
        public string TopText { get; set; } 
        public string TopFont { get; set; } 
    
        // SubObject (BottomObject) 
        public string BottomText { get; set; } 
        public string BottomFont { get; set; } 
    } 
    
    public class MainObject 
    { 
        public int Id { get; set; } 
        public string Name { get; set; } 
    
        public SubObject TopObject { get; set; } 
        public SubObject BottomObject { get; set; } 
    } 
    
    public class SubObject 
    { 
        public string SubPropText { get; set; } 
        public string SubPropFont { get; set; } 
    } 
    

定製值解析器

public class CustomResolver : ValueResolver<DTOObject, SubObject> 
    { 
     protected override SubObject ResolveCore(DTOObject source) 
     { 
      return Mapper.Map<DTOObject, SubObject>(source); 
     } 
    } 
+0

你有DTOObject設計的控制? – 2012-02-02 16:09:14

+0

是的,沒有這是一個大量使用的舊數據庫。 – 2012-02-02 19:47:31

+0

你試圖去哪個方向,DTOObject爲MainObject或MainObject爲DTOObject? – 2012-02-02 19:58:43

回答

3

我結束了創建我自己的值解析器針對來自DTOObjectMainObject任何子對象。

public class PartResolver<T> : ValueResolver<DTOObject, T> 
{ 
    protected override T ResolveCore(DTOObject source) 
    { 
     return Mapper.Map<T>(source); 
    } 
} 

然後在我的Automapper配置我創建一個從DTOObject地圖以SubObject並使用ValueResolver該對象映射到MainObject

Mapper.CreateMap<DTOObject, SubObject>(); 

Mapper.CreateMap<DTOObject, MainObject>() 
    .ForMember(dest => dest.SubPart, opt => opt.ResolveUsing<PartResolver<SubObject>>()); 
3

對我來說,可能只使用MapFrom(不解析使用什麼使您有機會使用IQueryable擴展的這種映射)。 所以你會得到在Automapper配置如下:

Mapper.CreateMap<DTOObject, SubObject>() 
    .ForMember(dest => dest.SubPropText, opt => opt.MapFrom(x => x.BottomText)) 
    .ForMember(dest => dest.SubPropFont, opt => opt.MapFrom(x => x.BottomFont)); 

Mapper.CreateMap<DTOObject, MainObject>() 
    .ForMember(dest => dest.SubPart, opt => opt.MapFrom(x => x));