2013-12-17 123 views
2

這裏是我的DTO:Automapper - 基於對象的類型設定值映射

public class DiaryEventType_dto 
{ 
    public Guid Id { get; set; } 
    public string Name { get; set; } 
    public string Group { get; set; } 
    public bool Redundant { get; set; } 
    public string Type { get; set; } 
} 

並將其映射到兩個可能的實體類型:

public partial class UserDiaryEventType 
{ 
    public System.Guid Id { get; set; } 
    public string Name { get; set; } 
    public string TypeGroup { get; set; } 
    public bool Redundant { get; set; } 
} 

public partial class SystemDiaryEventType 
{ 
    public System.Guid Id { get; set; } 
    public string Name { get; set; } 
    public string TypeGroup { get; set; } 
    public bool Redundant { get; set; } 
} 

「類型」屬性是爲了區分哪些DTO最初是從哪個類映射而來的(我爲什麼要這樣做,而不是有兩個獨立的DTO類?傳統代碼,這就是爲什麼 - 要改變它的太多痛苦)。

理想我想自動映射過程來填充它,否則,映射器會朝我扔一個搖擺,因爲「類型」未映射:

 Mapper.CreateMap<Entities.UserDiaryEventType, DiaryEventType_dto>() 
      .ForMember(m => m.Group, o => o.MapFrom(s => s.TypeGroup)); 
     Mapper.CreateMap<DiaryEventType_dto, Entities.UserDiaryEventType>() 
      .ForMember(m => m.TypeGroup, o => o.MapFrom(s => s.Group)); 
     Mapper.CreateMap<Entities.SystemDiaryEventType, DiaryEventType_dto>() 
      .ForMember(m => m.Group, o => o.MapFrom(s => s.TypeGroup)); 
     Mapper.CreateMap<DiaryEventType_dto, Entities.SystemDiaryEventType>() 
      .ForMember(m => m.TypeGroup, o => o.MapFrom(s => s.Group)); 

但我想不通的語法這樣做。例如:

//pseudo code 
Mapper.CreateMap<DiaryEventType_dto, Entities.UserDiaryEventType>() 
    .SetValue("User"); 
Mapper.CreateMap<DiaryEventType_dto, Entities.SystemDiaryEventType>() 
    .SetValue("System"); 

這可能嗎?

回答

3

ResolveUsing允許您使用自定義值或計算。

Mapper.CreateMap<Entities.UserDiaryEventType, DiaryEventType_dto>() 
     .ForMember(m => m.Group, o => o.MapFrom(s => s.TypeGroup)) 
     .ForMember(m => m.Group, o => o.ResolveUsing(s => "User")); 
相關問題