Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional projection using AutoMapper

Tags:

automapper

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.

like image 507
jaffa Avatar asked Jun 29 '11 14:06

jaffa


1 Answers

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;

    }
}
like image 56
ozczecho Avatar answered Sep 30 '22 10:09

ozczecho