2014-12-11 141 views
1

我有這個派對類,其中包含來自服務的object數據類型。它可以包含Item屬性的兩種不同的成員類型。Automapper,將一個對象成員類型映射到多個具體類型

public class Party 
{ 
    public string DMVID {get; set;} 
    public object Item { get; set; } 
} 

,這DTO

public class PartyDTO 
{ 
    public string DMVID {get; set;} 
    public BusinessDTO BusinessItem { get; set; } 
    public IndividualDTO IndividualItem { get; set; } 
} 

我怎樣才能在Item的輸出映射到BusinessItemIndividualItem。 我知道這一個不會工作。 Mapper.CreateMap<Party, PartyDTO>(); 我不知道條件映射是否可以解決這個問題或者像這樣的解析器one

回答

3

嘿,也許這會幫助你!我測試了它,但我只用了兩天就使用了AutoMapper!

好的,這裏是你的着名課程!

public class Party 
{ 
    public string DMVID { get; set; } 
    public object Item { get; set; } 
} 


public class PartyDTO 
{ 
    public string DMVID { get; set; } 
    public BuisnessDTO BusinessItem { get; set; } 
    public IndividualDTO IndividualItem { get; set; } 
} 


public class BuisnessDTO 
{ 
    public int Number 
    { 
     get; 
     set; 
    } 
} 

public class IndividualDTO 
{ 
    public string Message 
    { 
     get; 
     set; 
    } 
} 

並且在這裏你是這個當前場景的MapperConfiguration!

// Edit There was no need here for some conditions 
    AutoMapper.Mapper.CreateMap<Party, PartyDTO>() 
       .ForMember(dto => dto.BusinessItem, map => 
        map.MapFrom(party => party.Item as BuisnessDTO); 
       ) 
       .ForMember(dto => dto.IndividualItem, map => 
        map.MapFrom(party => party.Item as IndividualDTO); 
       ); 

    // And this is another way to achive the mapping in this scenario 
       AutoMapper.Mapper.CreateMap<PartyDTO, Party>() 
        .ForMember(party => party.Item, map => map.MapFrom(dto => (dto.BusinessItem != null) ? (dto.BusinessItem as object) : (dto.IndividualItem as object))); 

我爲它創建了這個示例!

  Party firstParty = new Party() 
     { 
      DMVID = "something", 
      Item = new BuisnessDTO() 
      { 
       Number = 1 
      } 
     }; 


     Party secondParty = new Party() 
     { 
      DMVID = "something", 
      Item = new IndividualDTO() 
      { 
       Message = "message" 
      } 
     }; 



     PartyDTO dtoWithBuisness = AutoMapper.Mapper.Map<PartyDTO>(firstParty); 
     PartyDTO dtoWithIndividual = AutoMapper.Mapper.Map < PartyDTO>(secondParty); 

     Party afterParty = AutoMapper.Mapper.Map<Party>(dtoWithBuisness); 
     afterParty = AutoMapper.Mapper.Map < Party>(dtoWithIndividual); 

當然還有其他的可能性,但我認爲那正是你想要的。

相關問題