7

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

目的地 :

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>()

在这里,我想将 my 映射Email.EmailRecipientEmailViewModel.To和的组合EmailViewModel.Cc。但是条件是,To 为Email.EmailRecipient.RecipientEmailTypeId1 , Cc为2

希望我的问题很清楚。

4

2 回答 2

5

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

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;
}
于 2015-07-07T19:34:11.870 回答
4

我是转换器的强烈反对者,主要是因为对于您项目中的其他人来说,在映射调用之后事情会像魔术一样发生。

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

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 属性,如果有人试图弄清楚它是如何发生的,他们只需要查看视图模型。

于 2015-07-07T19:41:27.173 回答