我有6个课程,我想用AutoMapper
进行mapp public class Alert
{
public string MessageSender { get; set; }
public Site Site { get; set; }
public IEnumerable<Recipient> Recipients { get; set; }
}
public class AlertModel
{
public string Sender { get; set; }
public SiteModel Site { get; set; }
public IEnumerable<RecipientModel> Recipients { get; set; }
}
public class Site
{
public int Id { get; set; }
}
public class SiteModel
{
public int Id { get; set; }
}
public class Recipient
{
public int Id { get; set; }
public string CallId { get; set; }
}
public class RecipientModel
{
public int Id { get; set; }
public string CallId { get; set; }
}
private static void ConfigureAlertMapping()
{
AutoMapper.Mapper.Initialize(cfg =>
cfg.CreateMap<Alert, AlertModel>()
.ForMember(dest => dest.Sender, opt => opt.MapFrom(src => src.MessageSender))
);
}
private static void ConfigureRecipientMapping()
{
AutoMapper.Mapper.Initialize(cfg => cfg.CreateMap<Recipient, RecipientModel>());
}
private static void ConfigureSiteMapping()
{
AutoMapper.Mapper.Initialize(cfg => cfg.CreateMap<Site, SiteModel>());
}
这是我要映射的对象。
Alert alert = new Alert()
{
Site = new Site() { Id = 1 },
Recipients = new List<Recipient> { new Recipient() { CallId = "1001" } }
};
我想打电话给这个,但抛出异常...... :(
AlertModel alertOutputInfo = AutoMapper.Mapper.Map<Alert, AlertModel>(alert);
这是错误:
>>Mapping types:
Alert -> AlertModel
UniteAlerter.Domain.Models.Alert -> UniteAlerter.Gateway.Models.AlertModel
at lambda_method(Closure , Alert , AlertModel , ResolutionContext )
at AutoMapper.Mapper.AutoMapper.IMapper.Map[TSource,TDestination](TSource source)
at AutoMapper.Mapper.Map[TSource,TDestination](TSource source)
at UniteAlerter.Gateway.AlertGateway.<SendAlert>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
如果您找到其他解决方案,请在此处添加。
答案 0 :(得分:0)
更新(解决方案)
我发现了问题...我为每个想要映射的类初始化mapper,但解决方案是使用所有映射初始化mapper一次。
AutoMapper.Mapper.Initialize(
cfg =>
{
cfg.CreateMap<Alert, AlertModel>().ForMember(dest => dest.Sender, opt => opt.MapFrom(src => src.MessageSender));
cfg.CreateMap<Recipient, RecipientModel>();
cfg.CreateMap<Site, SiteModel>();
}
);