自动映射器,将单个目标属性映射为多个源属性的串联 [英] Automapper, mapping single destination property as a concatenation of multiple source property

查看:99
本文介绍了自动映射器,将单个目标属性映射为多个源属性的串联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些情况下,我需要根据某些条件将单个属性映射为多个源属性的组合.

I have a situation where I need to map a single property as a combination of multiple source properties based on some conditions.

目的地:

public class Email
{
    public Email() {
        EmailRecipient = new List<EmailRecipient>();
    }
    public string Subject{get; set;}
    public string Body {get; set;}
    public virtual ICollection<EmailRecipient> EmailRecipient { get; set; } 
}

public class EmailRecipient
{
    public int EmaiId { get; set; }
    public string RecipientEmailAddress { get; set; }
    public int RecipientEmailTypeId { get; set; }
    public virtual Email Email { get; set; }
}

来源:

public class EmailViewModel
{
    public List<EmailRecipientViewModel> To { get; set; }
    public List<EmailRecipientViewModel> Cc { get; set; }
    public string Subject { get; set; }
    public string Body { get; set; }
}

public class EmailRecipientViewModel
{
    public string RecipientEmailAddress { get; set; }
}

我想要Mapper.Map<EmailViewModel,Email>()

在这里,我想将Email.EmailRecipient映射为EmailViewModel.ToEmailViewModel.Cc的组合. 但是条件是,对于 To Email.EmailRecipient.RecipientEmailTypeId将为1,对于抄送

Here I would like to map my Email.EmailRecipient as a combination of EmailViewModel.To and EmailViewModel.Cc. However the condition is, Email.EmailRecipient.RecipientEmailTypeId will be 1 for To and 2 for Cc

希望我的问题很清楚.

推荐答案

实现此目标的一种可能方法是创建一个使用特定方法进行转换的地图.地图创建将是:

One possible way to achieve this is to create a map that uses a specific method for this conversion. The map creation would be:

Mapper.CreateMap<EmailViewModel, Email>()
    .ForMember(e => e.EmailRecipient, opt => opt.MapFrom(v => JoinRecipients(v)));

JoinRecipients方法将自行执行转换的位置.一个简单的实现可能是这样的:

Where the JoinRecipients method would perform the conversion itself. A simple implementation could be something like:

private ICollection<EmailRecipient> JoinRecipients(EmailViewModel viewModel) {
    List<EmailRecipient> result = new List<EmailRecipient>();
    foreach (var toRecipient in viewModel.To) {
        result.Add(new EmailRecipient {
            RecipientEmailTypeId = 1, 
            RecipientEmailAddress = toRecipient.RecipientEmailAddress
        });
    }

    foreach (var ccRecipient in viewModel.Cc) {
        result.Add(new EmailRecipient {
            RecipientEmailTypeId = 2,
            RecipientEmailAddress = ccRecipient.RecipientEmailAddress
        });
    }

    return result;
}

这篇关于自动映射器,将单个目标属性映射为多个源属性的串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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