2013-12-17 95 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")); 
相关问题