自动映射器 - 根据映射的对象类型设置值

本文关键字:映射 对象 类型 设置 | 更新日期: 2024-10-25 15:53:26

这是我的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类?遗留代码,这就是为什么 - 太痛苦而无法改变这一切)。

理想情况下,我想在自动映射期间填充它,否则映射器会向我抛出一个摇摆不定的人,因为"类型"没有映射:

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

可能吗?

自动映射器 - 根据映射的对象类型设置值

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