1
我有6個班,我想與AutoMapper如何映射2個具有4個不同屬性類的對象?
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>());
}
到MAPP他們這是我要地圖的對象。
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()
如果你會發現另一種解決方案,請在此處添加它
你能否提供你的映射配置 – Shevek
當然,你需要向下滾動第一個代碼註釋(最後3個方法)。 – Alex
我將這些方法稱爲Configure,在Startup - > ConfigureServices(IServiceCollection services) – Alex