Conditional projection using AutoMapper

前端 未结 1 1922
忘掉有多难
忘掉有多难 2021-01-19 01:55

Say I have a \'Comment\' property on a \'Message\' class. I also have 2 class properties which have a \'Body\' property. If the class has either of the class properties se

相关标签:
1条回答
  • 2021-01-19 02:11

    Use a ValueResolver:

    .ForMember(dto => dto.Comment, opt => opt.ResolveUsing<CommentResolver>().FromMember(src => src))
    

    And then the actual implementation:

    public class CommentResolver: ValueResolver<Message, string>
    {
        protected override string ResolveCore(Message msg)
        {
            //logic goes here
            if (msg.InboundMessage != null)
             return msg.InboundMessage.Body; 
            else if (msg.OutboundMessage != null)
             return msg.OutboundMessage.Body; 
           else
             return msg.Comment;
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题