使用AutoMapper进行条件投影 [英] Conditional projection using AutoMapper

查看:60
本文介绍了使用AutoMapper进行条件投影的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我在消息"类上有一个注释"属性.我也有2个具有"Body"属性的类属性.如果该类设置了任何一个类属性,则我希望AutoMapper将Body属性投影到模型的comment属性中,否则在消息类上使用常规的comment属性.

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.

例如

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.

推荐答案

使用ValueResolver:

Use a 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;

    }
}

这篇关于使用AutoMapper进行条件投影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆