Conditionally mapping one source type to two destination types

后端 未结 4 784
遇见更好的自我
遇见更好的自我 2020-12-20 01:15

I have a source DTO like this

public class Member 
{
    public string MemberId {get;set;}
    public string MemberType {get;set;}
    public string Name {g         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-20 01:46

    I saw the example of conditionally mapping, but it maps the field it performs the conditional check on. I want to check the condition and map a different field.

    Try using such config:

    cfg.CreateMap()
        .ForMember(dest => PersonMember.PersonMemberId, opt => { 
            opt.Condition(src => src.MemberType == "Person");
            opt.MapFrom(src => src.MemberId);
         });
    cfg.CreateMap()
        .ForMember(dest => CompanyMember.CompanyMemberId, opt => { 
            opt.Condition(src => src.MemberType == "Company");
            opt.MapFrom(src => src.MemberId);
         });
    

    In case you mapping from a non-compatible object Id field will be set to 0.

提交回复
热议问题