Automapper - 根据映射的对象类型设置值

时间:2013-12-17 15:55:34

标签: c# automapper dto

这是我的DTO:

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; }
}

“Type”属性用于区分DTO最初映射的类型(为什么我要这样做而不是有两个单独的DTO类?遗留代码,这就是为什么 - 改变这一切太痛苦了)

理想情况下,我想在自动化过程中填充它,否则映射器会向我抛出一个摇摆器,因为“Type”未映射:

        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");

有可能吗?

1 个答案:

答案 0 :(得分: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"));