我想通过Automapper将mimeMessage_MailBox更改为email_MailBox实体,配置代码如下所示。
public static class AutoMapperConfiguration
{
public static void configure() {
Mapper.CreateMap<mimeMessage_MailBox, email_MailBox>()
.ForMember(dest => dest.SenderName, opt => opt.MapFrom(src => src.From.Mailboxes.ToString()))
.ForMember(dest => dest.EmailSubject, opt => opt.MapFrom(src => src.Subject))
.ForMember(dest => dest.EmailCC, opt => opt.MapFrom(src => string.Join(",",src.Cc.Mailboxes.ToString())))
.ForMember(dest => dest.ReceiverEmail, opt => opt.MapFrom(src=>string.Join(",", src.To.Mailboxes.ToString())))
.ForMember(dest => dest.EmailBody, opt => opt.MapFrom(src=>src.Body.ContentBase.OriginalString));
}
现在将数据保存到DbContext为
public void Save(mimeMessage_MailBox mail)
{
email_MailBox mailbox = new email_MailBox();
using (EmailEntityModelContext context = new EmailEntityModelContext())
{
context.email_MailBox.Add(Mapper.Map<mimeMessage_MailBox, email_MailBox>(mail, mailbox));
context.SaveChanges();
}
我是否必须在Save()方法中调用AutoMapperConfiguration.configure()? 还是有像DI魔术的东西? 请帮忙。
答案 0 :(得分:0)
Mapper.CreateMap()
Mapper.Map()
这些方法使用静态(全局)Automapper实例。因此,在每个应用程序生命周期内调用CreateMap
就足够了。
仅供参考:您可以创建其他映射器实例并控制其生命周期。阅读文档:Static and Instance API。