2012-02-02 6 views
4

무엇 작성이 question (Automapper 1.0)Automapper지도

  • 의 솔루션을 사용 Automapper 2.0 사용자 정의 값 리졸버를

    1. 를 내부 객체를 매핑하는 가장 좋은 방법은

    2. ?

      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의 디자인을 제어 할 수 있습니까? –

    +0

    예, 사용량이 많은 이전 데이터베이스는 없습니다. –

    +0

    어느 방향으로 가고 있습니까? DTOObject는 MainObject로, MainObject는 DTOObject로 이동 하시겠습니까? –

    답변

    3

    나는 DTOObject에서 온 MainObject의 하위 객체에 대한 내 자신의 가치 리졸버를 만드는 끝났다.

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

    그런 다음 내 Automapper의 설정에 나는 SubObjectDTOObject에서지도를 만들고없이 (그냥 MapFrom을 사용할 수 있었다 나를 위해 MainObject

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

    에 해당 객체를 매핑 할 ValueResolver를 사용 Resolve를 사용하면이 매핑을 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));