说我在'Message'类上有一个'Comment'属性。我还有2个具有'Body'属性的类属性。如果类具有任何类属性集,我希望AutoMapper将Body属性投影到模型的comment属性中,否则在消息类上使用普通的comment属性。
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; }
}
我没有在文档中看到任何处理此问题的内容。
答案 0 :(得分:5)
使用ValueResolver:
.ForMember(dto => dto.Comment, opt => opt.ResolveUsing<CommentResolver>().FromMember(src => src))
然后是实际的实施:
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;
}
}