gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:26:25 25 4
gpt4 key购买 nike

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

目的地 :

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至 和 2 表示 抄送

希望我的问题很清楚。

最佳答案

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

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

关于Automapper,将单个目标属性映射为多个源属性的串联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31220501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com