Automapper,将单个目标 属性 映射为多个源 属性 的串联

Automapper, mapping single destination property as a concatenation of multiple source property

我有一种情况需要根据某些条件将单个 属性 映射为多个源属性的组合。

目的地:

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 的组合。 但是条件是,Email.EmailRecipient.RecipientEmailTypeId 对于 To 为 1,对于 Cc

为 2

希望我的问题很清楚。

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

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

其中 JoinRecipients 方法将自行执行转换。一个简单的实现可能是这样的:

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;
}

我是转换器的强烈反对者,主要是因为对于您项目中的其他人来说,映射调用之后事情就会发生 'like magic'。

一种更简单的处理方法是将 属性 实现为一种将视图模型上的其他属性转换为所需格式的方法。示例:

public class EmailViewModel
{
    public ICollection<EmailRecipient> EmailRecipient { 
        get {
             return To.Union(Cc);
        } 
    }
    public List<EmailRecipientViewModel> To { get; set; }
    public List<EmailRecipientViewModel> Cc { get; set; }
    public string Subject { get; set; }
    public string Body { get; set; }
}

现在 automapper 自动从 EmailRecipient 属性 映射到 EmailRecipient 属性,如果有人想弄清楚它是如何发生的,他们只需要查看视图模型即可。