我有一种情况需要根据某些条件将单个属性映射为多个源属性的组合。
目的地:
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.To
和EmailViewModel.Cc
的组合。
但条件是,至 Email.EmailRecipient.RecipientEmailTypeId
为1; Cc
希望我的问题很明确。
答案 0 :(得分:3)
实现此目的的一种可能方法是创建一个使用特定方法进行此转换的地图。地图创建将是:
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;
}
答案 1 :(得分:3)
我是转换器的巨大反对者,主要是因为对于你项目中的其他人来说,事情就会发生,就像魔术一样。&#39;在映射调用之后。
更简单的处理方法是将属性实现为将viewmodel上的其他属性转换为所需格式的方法。例如:
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属性,如果有人试图弄清楚它是如何发生的,他们只需要查看视图模型。