Conditional projection using AutoMapper

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-09 03:36:21

问题


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.


回答1:


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;

    }
}


来源:https://stackoverflow.com/questions/6522569/conditional-projection-using-automapper

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!