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 set, I want AutoMapper to project the Body property into the comment property of the model, otherwise use the normal comment property on the message class.
e.g.
public class Message
{
public string Comment { get; set; }
public Inbound? InboundMessage { get; set; }
public Outbound? OutboundMessage { get; set; }
}
public class Inbound
{
public string Body { get; set; }
}
public class Outbound
{
public string Body { get; set; }
}
public class MessageModel
{
public string Comment { get; set; }
}
I've not seen anything in the documentation which handles this.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With